Preloading Content Using AS3

While most smaller Flash projects do not really need a preloader due to the today’s Internet speed, it is still good practice to always include a preloader in all your Flash projects. In this brief tutorial, I will demonstrate how to preload your Flash assets using AS3.

Preloading in AS3 is a more streamlined process due to the new & improved event handling structure that AS3 brings to the table. You have more control over what gets preloaded and when it gets preloaded.

How to Preload with AS3

Like most things in Flash, there are many ways to preload your content into your Flash projects. How you create your preloading animation will be totally up to you. In this example, I will be dynamically resizing a preloader’s fill based on the progress percentage of the content being loaded. It is a simple way to demonstrate a preloading action.

Code used in example

//Define a loader
var imageLoader:Loader;

function loadThisImage(url:String):void {
 //Show Preloader
 preloader.visible=true;
 imageLoader=new Loader();
 imageLoader.load(new URLRequest(url));
 //Add a listener to update the preloader on the image's progress
 imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,imageLoading);
 //Adding a listener that will update the preloader once the image has been loaded
 imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,imageLoaded);
}

function imageLoaded(evt:Event):void {
 // Load Image by adding it to the display list
 imageLoaderClip.addChild(imageLoader);
 // Hide Preloader
 preloader.visible=false;
}

function imageLoading(evt:ProgressEvent):void {
 // Get the current download progress
 var loaded:Number=evt.bytesLoaded/evt.bytesTotal;
 // Send progress info to "preloader" movie clip
 updateProgress(loaded);
}

function updateProgress(value:Number) {
 preloader.progress.width=value*preloader.bar.width;
}

//Loading the image defined in the parameter
loadThisImage("image-loaded-large.jpg");


As you noticed this example loads an image, but you can very well use it to load you main SWF content or even multiple images. By creating multiple loaders, you can then define the asset in which you choose to load.  This will allow you more control over your content being loaded.

As you can see,  preloading content using AS3 is actually pretty easy.  Have fun migrating over into AS3!

Download Source

I hope this helps in your migration over into  AS3.  If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.

Leave a Reply

Your email address will not be published. Required fields are marked *