Flash Preloader with Actionscript 3

Preloaders are used when the user will need to wait more than a few seconds to see the Flash content. This lets them know that something is coming and that there are no problems. Of course this is not an excuse for making bad, overweight (large file size) flash projects.

Types of Preloaders

While all preloaders are designed to let the user know that content is coming, there are several different types that designers will create.

What we need to know

In order to develop anything besides the basic animation, the designer needs to know two specific pieces of information. How big the SWF is, and how much has been downloaded by the end user.

Luckily Flash gives us that information in the for of a built in data object called the loaderInfo. To access loaderInfo, use this.loaderInfo, then they property you need to access.

bytesTotal - is the property from loaderInfo which stores the total size of the Flash SWF file.

bytesLoaded - is the property from which loaderInfo lets you know how much of the file has been loaded so far. This gets updated very often.

Setting up the Stage

This set up will assume a simple two frame Flash project. The first frame will be the preloader, the second frame the content.

You will need four layers. 1 for actions, one for the progress bar, one for the progress text, and finally one for the second frames content.

On the progress bar layer, create a rectangle (not in object mode) with a stroke. Convert the fill part of the rectangle into a movieclip. Make sure the registration point is on the far left side (not the center). Give it an instance name of progressBar.

For the text layer, add a classic text object. Give it an instance name of progressTxt.

Finally, make sure there is enough content on the second frame to spend some time downloading.

The Script

Step one is to stop the script on the first frame. Use the stop() command.

Next you will want to create an ENTER_FRAME event handler. After adding the listener, and assigning it to a function to server as the handler, you will need to get the size of your SWF, and how much has been loaded already.

var total:Number = this.loaderInfo.bytesTotal;
var loaded:Number = this.loaderInfo.bytesLoaded;

To figure out how much has been loaded as part of the whole (a percentage), you divide loaded from total.

var percent:Number = loaded/total; // this gives you a number between 0 and 1.