- Home
- Tutorials
- Flash
- Intermediate
- Preloading in ActionScript 3.0, the Easy Way

ActionScript 3.0 Event Handlers
(I’m assuming you know about the new ActionScript 3.0 event manager API so I’ll skip some details here).
The “loaders” job is to load the loadedmovie.swf file. As the loader “loads” the SWF file (we’ll see how this happens in a sec.), the ActionScript 3.0 event manager will continually fire off a “ProgressEvent.PROGRESS” event. We want to make sure our “loader” class listens for that event. We do this by using the addEventListener method, and we want to write an event handler to “handle” that event:
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loop);
I’ve called the event handler “loop.” The event manager continually calls this function as the loader downloads the SWF file. This the logical place to track the progress of the download:
function loop(e:ProgressEvent):void
{
var perc:Number = e.bytesLoaded / e.bytesTotal;
var s:String = Math.ceil(perc*100).toString()+"%";
percent.text = s
}
The ProgressEvent object passed to “loop” contains a variable called “bytesTotal” that holds the size of the loadedmovie .swf file, and “bytesLoaded” tracks how much of it has download each time the “ProgressEvent.PROGRESS” fires. Here I’m converting everything into percent, and I’m assigning that value (in string format) to the “percent” dynamic text field.
But we’re not done yet. When the loadedmovie .swf file is fully loaded, the event manager will then fire off an “Event.COMPLETE” event, so we want our “loader” to the listen for that event too:
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
“done” is the event handler. All it does is add the loadedmovie .swf file to the stage. It also does some clean up:
function done(e:Event):void
{
// 1st) remove each child from the display list so we don’t see them on the stage
removeChildAt(getChildIndex(percent));
removeChildAt(getChildIndex(arrows));
// 2nd) disable any running code in any child (see chap. 14, Moock, "Essential AS 3.0")
arrows.gotoAndStop(1); // stop looping
// 3rd set instance references to null so the garbage collector can remove them from memory
percent = null;
arrows = null;
// finally, add the loader to the stage to display it
stage.addChild(loader);
}

