R – How to tell when the main swf gets fully loaded

actionscript-3adobeflash

as I learned the hard way, Flash streams your .swf, that is, it can start playing back the file even if only the first couple of frames are loaded.

Normally, when loading an external .swf you would just register a handler to the COMPLETE event of the Loader or URLLoader class and that would be it.
Example (exception handling, etc. omitted):

var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.load(request); 

function completeHandler(event:Event):void {
    //trigger starting playback here
}

However, if the .swf file is the "main" swf, that is, the one referenced from the html, I can only access the root.loaderInfo property, that is, this:

root.loaderInfo.loader.addEventListener(Event.COMPLETE, completeHandler);

gives me the error The loading object is not sufficiently loaded to provide this information.

The workaround that does the job but makes me cringe is having a timer and polling the bytesLoaded property like this:

var Poller:Timer = new Timer(500, 0);
Poller.addEventListener(TimerEvent.TIMER, waitForLoad);
var e:Event;
waitForLoad(e);


function waitForLoad(event:Event):void {
 if (root.loaderInfo.bytesLoaded < root.loaderInfo.bytesTotal) {
     if (!Poller.running) Poller.start();
     return;  
 } else {
     Poller.stop();  
     completeHandler(event);
 }
}

There has to be a better solution than this. Ideally, I could register the event handler completeHandler to Event.COMPLETE to some property of the root or stage object and it would indeed throw this event when the file gets fully loaded…
Does anyone know which property it is?

Cheers,
Zoltan

P.S.: I am using Adobe Flash CS3

Best Answer

Instead of

root.loaderInfo.loader.addEventListener(Event.COMPLETE, completeHandler);

call

this.loaderInfo.addEventListener(Event.COMPLETE, completeHandler);

from the constructor of the document class.

Related Topic