Currently i need to know within JavaScript when a SWF-file was loaded completly. You could easily handle this with a single ExternalInterface call from within the Flash-application. This is not a very nice solution if this has to be done for each of you flash-applications. This is the neccesary way if you also have to access the flash-application from javascript-side. But in my case i just need to know when the flash is loaded and available in the browser cache.

For this i wrote the swfJSPreLoader. This preloader accepts an array of assets (jpg,gif,png,swf) you would like to preload. Internally it will create an flash-application which does the preloading. You could define several callback handlers. So JavaScript gets to know when all assets are loaded or each single asset is loaded including SWF-files.

<script type="text/javascript">
	var swfJSPreLoaderConfig = {
		'_swfPath':'./', // configure path to preloader SWF file
 
		'assets':[	'assets/teaser.swf',
				 	'assets/img2.jpg',
				 	'--error--'],
 
		'assetLoaded': function( asset, bytes, status ){
			alert( asset + ' loaded (' + bytes + ')' );
		},
 
		'loadComplete': function(){
			alert('all assets loaded. totally loaded bytes: ' + swfJSPreLoader.loadedBytes() );
		},
 
		'loadError': function(){
			alert('load error');
		},
 
		'callback': function(){
			swfJSPreLoader.addAsset('assets/teaser2.swf',function( status ){
															alert('teaser2 loaded status:' + status );
														});
		}
	}
</script>
 
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="swfJSPreLoader.js"></script>

To use the swfJSPreLoader you have to include three js files for swfObjects, JQuery and the swfJSPreLoader.js. You also have to define an JS variable swfJSPreLoaderConfig to configure the preloader. The config-variable could hold the following items:

  • assets: assets is an array of the assets which should be loaded. The asset-paths must be relative the html page. If you insert wrong asset pathes you could define an error handler. The assets array is optional. You could also add assets via method call.
  • assetLoaded: assetLoaded defines the callback method for each loaded asset. So this method will be called each time an asset is loaded completly. There are three parameters. asset – gives the asset-path; bytes – gives the number of loaded bytes of the current asset; status – gives the loading status ( 200: Ok, 404: Loading error )
  • loadComplete:The loadComplete callback method will be called after the queue of assets to load is empty. Not all assets need be loaded successfully. If not the error-callback will be fired.
  • loadError:The loadError callback will be triggered if the current asset could not be loaded correctly.
  • callback:With callback you could register a method which is called after the initialization of the swfJSPreLoader. After this method is called you could use the public methods of the pre loader.

There are two public methods of the swfJSPreLoader. Both methods are ready after the callback method is called and the initialisation is ready ( the loader flash is instanziated ).

swfJSPreLoader.addAsset: The addAsset method allows you to add a single asset to add to the loading queue. It takes to parameters. The first is the path to the asset, the second is the callback handler, which will be fired after this specific asset was loaded. The callback will also be called if the loading fails. The callback gets one argument status with the loading status ( 200: Ok, 404: Loading error ).

/**
 * @public
 *
 * adds asset to loading queue
 * @param {String} assetPath - path to assets to load
 * @param {Function} callback - optional callback handler when loading is complete
 */
addAsset:function( assetPath, callback )
swfJSPreLoader.addAsset('assets/teaser2.swf',
						function( status ){
							alert('teaser2 loaded status:' + status );
						});

swfJSPreLoader.loadedBytes: The loadedBytes method returns the number of total loaded bytes currently loaded bytes on each call.

Update 2011-08-07:swfJSPreLoader Flash Builder Project Sourcefiles (ZIP, 62kb)

Update 2010-05-17:swfJSPreLoader-Test (ZIP, 532kb)


Examples (added 2010-11-07, updated 2011-08-07)

After this seems to be difficult here are some more working examples. All tested at FF4.0b6/OSX; Safari5/OSX; Chrome7.0/OSX; FF3.6/WinXP; IE8/WinXP. Please not that this should be tested from an Server environment and not from local filesystem and requires an installed Flash Plugin.

Added an example for loading from other servers via crossdomain policy file and showing percent loading status.

download examples

I hope this is helpfull for anybody.

cheers,
Sebastian

33 thoughts on “ Preload assets with JavaScript, load-complete callback for single assets include SWF/Flash ”

  1. Hi,
    I exported to a SWF file something I made in After Effects and it loads a bit slow so I’m looking for a way to preload it or speed it up. I came across this tutorial. I’m having trouble getting it to work

    I’ve uploaded your examples here for testing
    http://www.franciscog.com/test/examples/

    I’m on Mac OSX 10.5.8
    I’ve tested on
    Chrome 7
    Firefox 3.6.12
    and Safari 5.0.2

    I have flash player 10 installed

    I just see the text that says „swfJSPreLoader…“ and the javascript pop-up boxes that tell me „Current Asset:…..“
    but no images or flash files ever load onto the page.

    thanks for making this available and hopefully I’m just overlooking something.

    1. Hi franciso,

      it will not show anything in the page itself. Its just a preloader for the browser cache. If it says the load is complete, the file you want to load is once loaded by flash and available in the browsercache. So if you now use this asset with you normal routine ( maybe via embedding it with SWFObject ) it should be immedialely there, because it comes from the browsers cache. But of course you have to implement the normal way of embedding the asset.

      cheers,
      Sebastian

  2. Hi francisco,

    this is in deed not the way it was meant to be. In your script you are loading it twice. Once by my preloader and once with the normal embedding.

    It’s more meant to be that the asset is loaded by the preloader. As soon as the preloader is finished you should start the embedding of the movie. In this case it will come from your browser cache.

    I your case this might also be not neccessary because you have only this one large asset the user has to wait for until it’s loaded.

    What you could do is to so some preloading of assets which will be used on you homepage, after the user saw your intro video.

    cheers,
    Sebastian

    1. Hi Adelchi,

      sorry i overlooked some comments. But better late reply than no.
      I just tested it with jQuery 1.6.2 and for me it was working fine. There should be no critical methods used. If you had any problems this must have other reasons.

      cheers.
      Sebastian

  3. Does the test app you provided work? It shows only „swfJSPreLoader“ bold, then „Here comes your content“ and nothing more. How can I check that it actually works?

    Thanks.

    1. Hi Takhir,

      sorry for my late reply. I overlooked some older comments and found them while cleaning my emails.
      It sound like you don’t run the script on serverenvironment. Because of the flash player security model this must not run from file:// but http://localhost/ or http://mydomain.com/.

      I also put the latest examples on my server for testing:
      05-dynamically-add-asset.html
      06-preloader-crossdomain.html

      You should get some alert boxes in 05 and a upcounting %-value in 06.

      cheers.
      Sebastian

  4. Can you please let me know how to embed the swf after the preload? Does the swfJSPreLoader.addAsset method do that piece? An example on how you actually embed something that you have preloaded would be much appreciated.
    Thank you,

  5. Very nice piece of script Sebastian, very appreciated.

    I would like to know if there is a way to accept the swf from another url (for example a subdomain, or a cdn network). Do I have to configure a crossdomain.xml? I tried to load it with an absolute url, but the swf won’t load.

    I can pay you for making this modification and a couple extra I have in mind, as an incentive and also as a donation for your work to the js community.

    You can of course then publish your work here, but I understand it must be hard to start reading all this code again and your time and effort needs to be rewarded somehow by someone. I can’t pay you that much because I am on my own, but I can offer some bucks to you as a donation.

    Please contact me,

    Pablo

  6. I’m trying to use your swfpreloader as in your example 06-preloader-crossdomain.html. If i test it on htt://localhost/preloader/06-preloader-crossdomain.html it works, but if i`m trying to integrate it in cakephp on the callback function swfJSPreLoader.loadedBytes() returns only 0 as value. (and the loadedPercent changes only when the assets loads 100%)

    1. Hi Andrew,

      i just wrote you a mail. Do you have a testserver i could check this ?

      UPDATE:
      I got access to a testserver. The version of the SWF-file was not the latest one, so the update event, which was added later, wasn’t fired.

      cheers.
      Sebastian

  7. Hello Sebastian, your script is awesome , you have done a very good job. after i integrated to my website i was thinking if it was possible to fire the swf file not when is 100% downloaded but 50% , is this possible? thanks

    1. Sorry andi, but there are no events thrown during the loading process showing you exactly 50% (or sth else ). But if you know the size of your file you could regularly call the swfJSPreLoader.loadedBytes method so you see how many bytes are loaded and you at least know if you already have loaded less or more than 50%.

      cheers.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert