Tutorial: A Simple Preloader, in detail
Preloaders are one of the simplest bits of underutilized Flash programming
on the web. When making any kind of presentation on the web, whether it be
an interactive experience or a self-running animation, it is important to consider
user experience. It is important to be generous with the user, because we ask
that they be generous with us as they view our websites. Preloaders are also
important because they may retain busy or impatient users who would otherwise
think that nothing is going on when the page is merely loading without giving
feedback.
Not everybody’s a programmer, though. So I’ve provided this detailed tutorial
for anyone would like to add a preloader to their Flash web project.
Getting started:
I usually like to put the preloader in its own scene so that it doesn’t disturb
my main timeline. If you’re not familiar with using scenes in Flash, a scene
can be added in the following manner:
- Window > Other Panels > Scene
- click the “+” to add a new scene
- drag it to the top
- and double-click to rename it
- I usually name it “preloader” and from hereon out I will refer to
it as the preloader scene
Then make sure your actionscript is organized in its own layer in the preloader
scene:
- add a new layer and rename it to ‘actions’
- lock the layer so nothing accidentally get placed on the stage for this layer
- select the first keyframe on the actions layer and open the actions panel
- the actions panel can be opened by hitting the f9 key or by going to Window > Actions
Then enter the following code:
//percent_txt is a dynamic text field
//note the 3 different display options (A, B, C)
stop();
loaderbar_mc._xscale =
0;
function preloading():Void{
var bLoaded:Number = getBytesLoaded();
var bTotal:Number = getBytesTotal();
var percentL:Number = (bLoaded / bTotal) * 100;
if (percentL < 100){
// (A) if you want to show text in the form of xx% loaded
percent_txt.text = Math.round(percentL) + “% loaded”;
// (B) if you want to show text in the form of xx Kb loaded/ xx Kb total
percent_txt.text = Math.round(bLoaded/1000) + ” Kb / “ + Math.round(bTotal/1000) + ” Kb” ;
// (C) if you want a loaderbar to grow with the % loaded
loaderbar_mc._xscale = percentL;
} else {
clearInterval(loaderInterval);
play();
}
}
loaderInterval = setInterval(preloading,25);
//make sure there’s a stop command on your main scene if it’s a one frame app
Now for a detailed description of what everything does:
stop();
The stop() command tells the playhead to halt but allows the code on the stopped
frame to run.
loaderbar_mc._xscale = 0;
This code initializes the ‘_xscale’ property of an instance with the name
‘loaderbar_mc’ so that it has no width (because the movie has just begun loading).
This is basically a rectangular movieClip. The instance name is applied via
the properties inspector panel. Select the loaderbar movieClip on the stage
(it needs to be in the preloader scene if you chose to do this the way I’ve
listed). Make sure your symbol is a movieClip. Graphic symbols cannot have
instance names and are therefore inaccessible with ActionScript.
function preloading():Void{
var bLoaded:Number = getBytesLoaded();
var bTotal:Number = getBytesTotal();
var percentL:Number = (bLoaded bTotal) * 100;
This is the beginning of a custom function that I’ve written called ‘preloading’.
The word ‘function’ is used to begin the function, then the function name.
The parentheses are empty because no variables are being sent to the function.
The word ‘Void’ tells the application that the function is not returning any
variables, and the curly bracket begins the content of the function.
The next 3 lines are variable declarations. The ‘:Number’ is what’s called
strict data-typing. It tells Flash that this variable should be a number. If
I try to load it with a string variable (“atom” for instance) or
a boolean value (TRUE or FALSE), Flash will report an error in the output panel.
The first variable retrieves the bytes loaded by Flash, the second retrieves
the total bytes, and the third divides the current loaded bytes by the total
bytes to get a percentage (multiplying by 100 gets it into the form we’re used
to, like 56 instead of .56–we’ll add the percent sign next).
if (percentL < 100){
// (A) if you want to show text in the form of xx% loaded
percent_txt.text = Math.round(percentL) + “% loaded”;
// (B) if you want to show text in the form of xx Kb loaded/ xx Kb total
percent_txt.text = Math.round(bLoaded/1000) + ” Kb / “ + Math.round(bTotal/1000) + ” Kb” ;
// (C) if you want a loaderbar to grow with the % loaded
loaderbar_mc._xscale = percentL;
}
This next block is an ‘if’ statement. The content of the if statement is contained
in curly brackets just like our function (which we are still inside). The code
inside the parentheses is the statement that drives this command; as long as
it’s true, the lines inside the if statement’s curly brackets will continue
to run. In this case it’s checking to see if the percentL variable we created
in the previous line is less than 100.
The lines that begin with ‘//’ are merely comments for reference, they have no affect on the code. They represent 3 different
options I have provided for displaying feedback to the user. They can be used
seperately or in combination. Make sure to delete the items you don’t use or
comment them out by adding two slashes (‘//’) at the beginning of the line.
The ‘percent_txt’ refers to a dynamic text box on the stage with the instance
name ‘percent_txt.’ This text box must be set to ‘Dynamic text’ in the Property
Inspector to give it an instance name that we can reference with ActionScript.
I usually choose a web font (verdana or arial) and select ‘Use device fonts’
from the Property Inspector. This utilizes the user’s own fonts and keeps the
Flash file size low. The alternative is embedding a font, and depending on
the font, that can add a lot of girth to an swf.
The first two options (A and B) are merely concatenations (lumping bits together
into a string of text). I use Flash’s built-in Math.round function to round
to whole numbers for a less cluttered display. The third option (C) uses the
‘percentL’ variable that was created earlier to determine the size of our loaderbar_mc
movieClip, hence the loaderbar will seem to grow.
Finally we close out the ‘if’ statement with a curly brace.
else {
clearInterval(loaderInterval);
play();
}
Next, we use an ‘else’ statement to clear the ‘loaderInterval’ (which I’ll
explain in a second), and play() the main timeline (i.e., start the movie).
The else statement is what gets called when the condition within the if statement
(percentL < 100), is no longer true (because the movie is completely loaded,
100%).
}
loaderInterval = setInterval(preloading,25);
Finally we close out the function with a curly bracket and we’ve come to the
interval. An interval is something that occurs repeatedly until it’s cleared.
This is an alternative to using ‘onEnterFrame.’ I’ve stopped using onEnterFrame
because I like the versatility of using intervals.
This bit of code actually gets called before the ‘preloading’ function, because
a function must be called in order to run. In this case the preloading
function is getting called every 25 milliseconds or 40 times/second. This allows
for smooth animation of the loaderbar even if the swf is only set to 12 frames/second.
Whereas, onEnterFrame will only run at the document’s frame rate.
First we need to declare
the interval with a variable name so that it can be referenced and cleared
in our ‘else’ statement, hence ‘loaderInterval.’ Next we use the setInterval
function and two of its paramenters to call the preloading function from above
every 25 milliseconds. That means that ‘preloading’ will be called over and
over until the percentL variable reaches 100.
Clearing the interval is important
because it is memory intensive to have the user’s CPU calling a function over
and over, especially when other things are occurring within the swf. That’s
why we clear the loaderInterval once we’re done using it. I called this variable
‘loaderInterval’ because that’s its purpose in this code, but an interval can
be named just about anything.
Testing The Preloader
To test your movie go to Control > Test Movie. You’ll notice the preloader
scene shows very quickly if at all. That’s because we’re testing it locally.
To see what it would look like in action go to View > Simulate Download. You
can change the speed of the connection that’s being simulated by going to View
> Download settings and selecting a different speed.
That’s it!
A quick note:
This preloader code is designed for ActionScript 2 (Macromedia Flash MX 2004
or later, Flash player 6/7 or later). To make this code function in ActionScript
1, remove all of the strict data-typing (basically everything beginning
with a colon–:Number and :Void).
Happy Flashing!
-Justin





It was brought to my attention that what we commonly refer to as a kilobyte is actually 1024 bytes (more accurately known as a kibibyte). For the most accurate byte totals use 1024 instead of 1000 in display option B. For most files, this will not constitute a huge difference, but this is an important distinction to note.
Thanks to NSurveyor for the catch.
For more info, see the Wikipedia entry on Kilobyte.
Comment by Justin — February 20, 2007 @ 6:42 pm
you did a great job. The info is greatly appreciated
Comment by kids games online — August 27, 2010 @ 8:20 pm