Making the complete internal preloader in Flash 8, with a
loading bar and mathematical preloaders
In this tutorial, you will see how easy it is to create an internal preloader
for your Flash site, complete with:
A graphical loading bar,
An animated text field showing the percentage of your Flash movie loaded
so far and,
A dynamic text field showing the amount of bytes loaded and total bytes.
Moreover, you are going to learn:
What are functions
What are function calls and how to implement them
How to display text in a dynamic text field
How to move a movie clip via ActionScript
You will also see how to make your preloader disappear and proceed onto the
site once it has been loaded completely. The example below shows what you are
going to learn to make with this tutorial (it is a rough animated representation
of the real preloader you are going to create).
Creating the loading bar and the dynamic text field
1. Open a new Flash document. Call the first layer
loading bar.
2. Select the Rectangle tool (R) and block
the Outline color. You can see a detailed explanation on how to do this in step
2 of my tutorial on making
a mirror menu.
Draw a 150 by 5 pixel rectangle and center it on stage.
Making a rectangle with these precise dimensions can be difficult with free
hand drawing, so I suggest that you adjust these values manually by entering
them in the appropriate fields in the Properties panel (with the ractangle
selected, of course). You'll find the width (W) and height (H) input fields in
the bottom left part of the aforementioned panel.
3. Select the rectangle by clicking on it with the Selection
tool (V). Select Modify > Convert to Symbol
to make a movie clip out of your rectangle.
In the dialog window that appears, select Movie clip as type and call it
blue loading bar. Well, you can call it anyway you like, I called it
like that because I used blue as the color for the rectangle. Just don't make it
white if your movie background is white too :)
Now, one important thing! In the registration portion of the Convert to
Symbol window, click the middle left rectangle (see it on the image below). This
will be the movie clip's registration point. You may click OK now.
Why is this necessary, you may wonder? Well, the loading bar shows how much
of your Flash website remains to be loaded. And it makes sense that it stretches
from left to right, right?
You may eventually choose to make your loading bar stretch to both sides, or
from right to left, but I will stick with the standard left-to right in this
lesson.
To see what difference makes the selection of left and central registration
points for a movie clip, just look at the flash example below.
4. Fine. With your newly made movie clip still selected on
stage, go to the left side of the Properties panel below the scene and assign it
an Instance name. Call it loadingBar.
5. Lock this layer. Make a new one and call it bytes
info.
6. Select the Text tool (T). Go to the
Properties panel once again, and select the following properties for your text
field:
Set the type to Dynamic text (see 1 in the image below).
Select _sans as font type (it should be on top of the fonts
list). This means that once a visitor comes to your site, his computer will
automatically select its system's default sans serif font - Arial for Windows
and Helvetica for Mac.
Select the central alignment for your text field (you can choose some
other type of alignment, but central is nice since your text field will thus
be centrally aligned with the loading bar above it).
Select the Use device fonts option. Why? Simple:
In this way, you don't have to embed the characters in your text field
(because the font will be read directly from the user's machine) and this
makes your SWF smaller in filesize.
You're also making the first frame of your movie lighter, which is
important, because you want it to load immediately. If a user sees a blank
screen (suppose the first frame with your preloader is heavy with font
characters and graphics)
Leave the "selectable text" option turned off. Why would anyone want to
select (and even copy) the text which tells how much bytes remain to be
loaded?
7. Click and drag out a text field just below the loading
bar.
Hit Esc to exit text editing mode.
8. Set the position coordinates of your text field to round
numbers (see 6 in the big image above). This will make the text in the field
render properly, you will avoid any blurry characters.
9. Give this field an Instance name, otherwise you won't be
able to tell it what to display via ActionScript commands. Call it
bytesDisplay.
Lock this layer.
Creating the text field with percentage information that is going to be
animated
10. Make a new layer and call it arrow
indicator.
11. Draw a nice small triangle just above the loading bar's
left edge. NOTE: Once you locked its layer, the dynamic text field isn't
visible. But don't worry - it is still there :)
If you don't know how to create a precise little triangle like the one in the
image above, I'll show you quickly how to do it here:
Draw a borderless square with the Rectangle tool (R) by
holding Shift while clicking and dragging your mouse.
Rotate the square by 45 degrees with the Free Transform tool
(Q).
Select the Line tool (L) and draw a line from the
square's left to its right point. To do this exactly from edge to edge, be
sure to have the Snap to objects option turned on (the small magnet icon at
the bottom of the Tools panel).
By using the Selection tool (V), select the upper portion
of the rectangle and hit Delete.
Select the line and erase it too.
The following figure displays the sequence of these steps:
To make life easier, draw a big square and once you have obtained the
triangle, just make it smaller either with the aid of the Free Transform tool
(Q) or by entering its dimensions manually in the Properties
panel.
Also, be sure that the triangle is positioned on round coordinates (like you
did with the text field previously) so that it renders sharply. After you did
that, move it to its final position with the aid of the arrow keys on your
keyboard. By doing that, you can move the triangle around and it will stay on
round coordinates - the arrow keys move your objects exactly by 1 pixel at a
time.
12. With the triangle still selected, press
F8 (or select Modify > Convert to Symbol)
to convert it to a movie clip.
Call it moving percentage field and make sure that the registration
point is on its left middle side.
13. Double-click on the newly made movie clip on stage to
enter inside it. You know that you are inside the movie clip now (working on its
timeline and not the main scene) if you look above the layers.
14. Call this layer (inside the movie clip, yes)
arrow.
15. Select the triangle drawing and move it so that its
bottom point is centrally aligned below the movie clip's registration point.
The line seen in the image below is the loading bar on the main scene, which
is seen as faded because you entered inside the movie clip - everything on the
main scene is a little bit faded, to make the distinction between these objects
and the ones inside the movie clip, so don't let that confuse you.
Why you must make this so? Because the percentage text field and the arrow
will move as the loading bar progresses. To be able to have the arrow always
placed at the loading bar's right edge, you are making these adjustements
now.
16. Lock this layer. Make a new layer above it and call it
text field.
17. Select the Text tool (T), click and
drag to create a small text field just above the triangle.
18. Leave all the properties for the dynamic text field the
same as they were for the first one you created. Just make a small adjustement:
set the alignment for the text field to left.
The left aligned text will stretch to right as the movie loads and the
information changes (for example 3%, 15% and 100%), instead of stretching to
both sides if it were centrally aligned. This wouldn't look so good while the
movie clip is moving parallelly with the loading bar, hence this change.
19. Give this text field an Instance name: call it
percentDisplay.
20. Lock this layer. Click on the Scene 1 link above the
layers to return to the main scene.
21. Use the arrow keys to adjust the position of the
moving percentage field movie clip. Place it so that the blue triangle
points at the loading bar's left edge.
22. Finally, give this movie clip an Instance name: call it
percentClip.
Lock this layer.
Placing in the site content
23. Make a new layers on top of all the existing ones and
call it content.
24. Right-click on this layer's frame 5 and select
Insert Keyframe from the menu.
This keyframe will hold the site's content for this lesson. In a project for
a real website, you can have as many layers as you want. Just make sure that
every layer that is hosting content is empty until its frame 5. Don't place any
site content on the first keyframe, because this particular frame is resereved
for the preloader elements only.
If any of the layers' first frames hosted any content, you would get a bad
flash site at the end. Because the user would wait for this content to load,
together with the preloader elements. Right now, the first keyframe is only 1 KB
in size, which is excellent, because this means it will load instantly, even on
a slow modem connection!
The preloader must load at once, otherwise you risk
losing your site (or worse, your client's) visitors.
25. You should place some content here now. The best thing
to simulate content is an image. Find an image that is about 100-150 KBs in
filesize. If you don't have one handy now, download
the image I made for this tutorial.
Unpack the image (it is zipped). Put it somewhere you'll find it quickly.
26. Select File > Import > Import to
Stage. Select the picture you want to import and click Open. The
picture will appear on your main scene.
Fine. This image will make for some dummy content to simulate the download
later.
27. Make a new layer and call it actions.
28. Select the first keyframe of this layer by clicking on
it.
29. Press F9 (or select Window >
Actions) to open the Actions panel. Enter the following ActionScript
code inside it:
stop(); loadingBar._xscale = 1; var loadingCall:Number =
setInterval(preloadSite, 50); function preloadSite():Void { var siteLoaded:Number = _root.getBytesLoaded(); var siteTotal:Number = _root.getBytesTotal(); var percentage:Number =
Math.round(siteLoaded/siteTotal*100); loadingBar._xscale = percentage; percentClip.percentDisplay.text = percentage +
"%"; percentClip._x = loadingBar._x +
loadingBar._width; bytesDisplay.text = "loaded " +
siteLoaded + " of " + siteTotal + " bytes"; if
(siteLoaded >= siteTotal) { clearInterval(loadingCall); gotoAndStop(5); } }
30. Test your movie by selecting Control > Test
Movie. The site will load instantly, of course, because it loads
straight from your hard disk and not from some web server. To see the preloader
in action, execute the nest step.
31. While still in test movie mode, select View >
Download Settings > 56K. This will set the simulated speed of
download to a standard (slow) 56K modem. Which is fine, to see how an average
modem user sees the preloading progress of your site.
32. Still in movie testing window, select View >
Simulate Download. You will now see the preloader at work! Wow! :)
Before moving on, just make the following: whether your movie has fully been
loaded or not, select View > Bandwidth profiler. You will
see the following graph appear above of your movie:
This is the Bandwidth profiler, which gives you the opportunity to look at
some interesting information about your SWF movie.
For each of the frames in your movie, there is a gray column representing it.
Notice the first gray column (I marked it with a red arrow in the image above).
This column represents the very first frame of your movie.
When making a preloader, the first frame is the most important one. You can
see in the image that all the elements for the preloader (graphics, text fields,
ActionScript code) are less then 1 KB in size! Which is great, because a
preloader must load immediately.
Try to make your preloaders no bigger than 3 or 4 KB. In that way you can be
sure that the average modem user will see it instantly. If you make your site
visitors wait because the preloader itself takes too long to load, they may well
leave your site thinking something's wrong with it (and never come back
again).
On the other hand, if you are making a specific Flash website that targets
broadband users (with a DSL or faster link), the preloader can be bigger in
size.
Then you can put more graphics in your preloader and make it more
sophisticated. But nice and effective design can be achieved by using the Flash
authoring tools only - keep that in mind.
Now that you learned how to design and plan your preloaders, let me explain
you what makes it tick.
The ActionScript code explained
The first thing that you tell Flash to do is to stop the movie from going on.
In this way, the playhead doesn't go forward. If it went forward, your site
visitor(s) would see nothing, because the SWF movie hasn't loaded yet. That's
why you have to stop it.
stop();
The next line,
loadingBar._xscale = 1;
sets the _xscale property of the loadingBar movie
clip to 1. What is this property? First, this is a percentage value. So, 1 in
the line above means actually 1%.
By default, when a movie clip hasn't been manipulated via ActionScript, its
_xscale property is set to 100%. Your loading bar has a width of
150 pixels (if you set it to this width, like I suggested in this tutorial). If
you make its _xscale property equal 50, it means that its width
will become reduced to 50% of its original value, therefore 75 pixels.
You have put this value for your loading bar to 1, because in the moment
before your movie starts preloading, you want the bar to be at the smallest
possible value.
Now comes a setInterval method that calls a function in regular
periods. To explain it, I first need to explain you what a function is.
var loadingCall:Number = setInterval(preloadSite, 50);
A function is a set of ActionScript commands that are grouped together. Ok,
but what does that exactly mean?
Imagine this: you are working in a fruit juice factory. There is a computer
that tells the juice mixers what kind of juice must be made and poured in
certain bottles. So you have different functions programmed inside this
computer, for different kinds of juices. Let's say you want to make a tropical
juice (yum!). You would have a function in that computer that would tell it to
mix different juices together, to have the tropical mix in the end. In
ActionScript, this would be something like this (this is just a fictional
example):
Ok. So that computer function would produce the tropical juice. But would it
run by itself? No. Someone who operates the computer would have to press a
button in order for the juice production to begin.
The same is with an ActionScript function: it just sits there and
does absolutely nothing unless you call it and make it execute its
code!
Doesn't matter if your movie is playing or if it is stopped. The function
won't run unless you tell it to. So, how to make it execute? To run a function,
you must call it. A simple function call looks like this:
tropicalJuice();
And that's it. You just write the function's name followed by parentheses and
a semicolon and it runs every command that is placed inside its curly braces -
{ and }.
But it is run just once. After doing that, it is again just waiting and doing
nothing until you call it again. With your preloader that would be inconvenient.
The function must check how much of your SWF has been loaded continuously, if
you wish your preloader to work.
So here's a nice ActionScript gizmo that comes in handy: a
setInterval method. This method (a command is called a method in
programming jargon) can call a function at regular time intervals. This method
must be placed in a variable, hence the line
var loadingCall:Number = setInterval(preloadSite, 50);
So, the first part, var loadingCall:Number tells Flash to create
a variable (var), name it loadingCall and make it a
Number kind of variable.
I could have called it callMyFunction or
runPreloading, I just chose loadingCall because it
sounded good to me. The Number keyword tells Flash to make this
variable a, well, Number kind of variable. This means that this variable isn't
one which will hold a text or any other kind of value, but exclusively a
numerical one.
On the right side of the equals sign, there's what the
loadingCall variable will hold inside it. The
setInterval method has two values inside its parentheses: the first
one is the name of the function you want to call (preloadSite in
this case) and the second one is the time interval at which the function will be
called regularly.
This time interval is expressed in milliseconds. If you wanted your function
to be called every second, you would have written 1000. Since this is too slow a
check for a preloader, 50 is a better value. It means the function will be
called every 0.05 seconds, which is pretty often and pretty fine.
So, as soon as Flash reads that line of ActionScript, it will immediately
start calling the function mentioned inside it, at the designated time
intervals.
Now comes the function (I will explain its contents later):
function preloadSite():Void { ...ActionScript commands go in here... }
The function's first line defines it and gives it a name - function
preloadSite. After the parentheses and the colon comes the keyword
Void. This keyword tells Flash that this function does not return
any value.
There are functions that return a value, like a sum of two numbers for
example, but this one you're making returns nothing. And you must tell that
Flash too. Yep, this is how ActionScript 2.0 works. Everything is precisely
defined, that's why ActionScript is a strictly typed
programming language.
Let's see what's inside it. The first two lines define two variables, which
are both numerical:
var siteLoaded:Number =
_root.getBytesLoaded(); var siteTotal:Number =
_root.getBytesTotal();
The first, siteLoaded, will hold the number of bytes loaded so
far. The keyword _root means the main timeline - the SWF movie
itself. Therefore, _root.getBytesLoaded means "see and fetch the
number of bytes of this SWF flash file that have been loaded up to this point".
And then this value is put inside the siteLoaded variable.
The siteTotal variable is similar to the one preceding it: it
does the same, except that it holds the total file size (in bytes, of course) of
the SWF movie, that has to be loaded.
The percentage variable,
var percentage:Number =
Math.round(siteLoaded/siteTotal*100);
holds the resulting value of the operation on the right side of the equals
sign. There is the number of bytes loaded so far (siteLoaded)
divided by the total number of bytes (siteTotal) and multiplied by
100. This is the basic percentage formula in maths - divide part by whole,
multiply by 100 and you get the percentage.
And there's the Math.round method which rounds the resulting
number between the parentheses. I recommend that you use it because you
certainly don't want something like 24.6012837% appearing in your text field.
This may look cool or sci-fi like, but in reality this just confuses the user
because it is harder to read than a round number (24%).
Now that percentage value gets used in a most interesting and cool way:
loadingBar._xscale = percentage;
Remember loadingBar? It is the Instance name of the loading bar
movie clip - the graphical element of your preloader. So by telling Flash that
loadingBar's _xscale property should equal percentage,
you make it stretch as the movie loads.
If the movie has loaded up to, say, 50% by now, that information is stored in
the percentage variable and then applied to the
loadingBar movie clip. So once the movie has fully loaded (100%),
this bar will come to its final size - 100%.
Each time the function is called (0.05 seconds), the percentage value gets
updated, and the loading bar stretches together with it. Now ain't ActionScript
awesome? You can do anything you want with it. I love Flash!
Onwards. The following piece of code defines what is going to be displayed in
the percentDisplay text field, which is itself situated in the
movie clip called percentClip.
To help you remember where this text field is, here's a little visual
clue:
If you just wrote
percentDisplay.text
this wouldn't produce any result at all, because Flash would look for that
textfield on the main (_root) timeline. Since this textfield is in
a movie clip, you have to write
percentClip.percentDisplay.text
And the text that is going to be shown inside it is the value of
percentage variable, plus a little percentage sign (%) after it.
So, when the loading of your site has reached 34% for example, Flash joins the
number 34 with the % sign and displays it.
Now comes the part where the aforementioned clip (the one on the picture
above, with the arrow and the textfield) moves as the loading bar progresses.
The clip's horizontal position (_x) is calculated by making a
sum of the loadingBar movie clip's horizontal position
(loadingBar._x) and its current width
(loadingBar._width). Like this:
In this way, the percentClip is always placed on the right edge
of the loading bar.
This one is easy: it displays some information in the text field below the
loading bar. The text between quotation marks is displayed literally, as written
inside the ActionScript code, and the siteLoaded and
siteTotal are variables defined at the beginning of the function,
and their respective values are displayed. This text fields tells the user how
many bytes have been loaded so far of the total bytes the site has.
The conditional if statement runs what's inside its curly braces
only if it gets to be true.
if (siteLoaded >= siteTotal)
{ clearInterval(loadingCall); gotoAndStop(5); }
Translated into English, this means that if the number of loaded bytes
(siteLoaded) is equal or greater then the total number of bytes of
the movie that is being loaded (siteTotal), the two lines of code
which follow get executed.
clearInterval(loadingCall);
The loadingCall interval that used to call the function every
0.05 seconds is stopped with the clearInterval method. Why? Because
you don't need this anymore. All of your movie has been loaded - it can leave
the preloader and proceed onto the frame where the content lies:
gotoAndStop(5);
And that's it! Whew!
You learned a lot of ActionScript, which is excellent. Keep on going like
that! If you are interested in different kinds of preloaders, like the ones with
a mask, or that replace your mouse, check out my other tutorials
on preloaders.
Below you can download the source file for this lesson.