Actionscript 3 External Preloader
Wednesday, December 19th, 2007A preloader is an important part of any sizeable Flash app as you probably don’t want your users to see nothing while the app’s loading. There are two types of preloaders that you can employ: external and internal. In this tutorial we’ll see how to implement External Preloaders, which load the contents from a separate file. This method is much cleaner and easier than the internal way, so I recommend you use it whenever you can. It also allows you to keep your preloader and main content independent of each other.
The general idea is to set up a Loader object in your preloader SWF, and make it execute 2 functions: an update function, and a finish function. The update function is called every time load progress is made, and the finish function is called when loading is done. You would accomplish this through Event Listeners as follows:
var request:URLRequest = new URLRequest("Content.swf");
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
What you do inside those functions is totally up to you. If you have a loading animation that animates relatively to the progress (like a cup filling up), then you would update that animation inside the loadProgress function. But as an example, we’ll be updating a percent counter as the load progresses.
function loadProgress(event:ProgressEvent):void
{
var percentLoaded:Number = event.bytesLoaded / event.bytesTotal;
percentLoaded = Math.round(percentLoaded * 100);
this.percentLoaded.text = String(uint(percentLoaded)) + "%";
}
function loadComplete(event:Event):void
{
trace("Load Complete");
}
To wrap it all up, we call load on the URL request, and add the Loader object to the preloader’s Display List, so that the content shows up when it’s done loading.
loader.load(request);
this.addChild(loader);
Also, make sure that the preloader’s dimension and frame rate settings are the same as the main content’s.
Here are the source files with the external preloader, and a test content SWF.


