Flash CS3 Tutorial – ActionScript 3 Preloader

April 28th, 2008 | 77 Comments

hourglassThere is very little that will push users away quicker than a bulky Flash website with no preloader. Without a preloader, your users will have nothing to look at but a blank screen until your Flash file has fully loaded. For users with a speedy broadband connection, this may not be much of an issue (depending on the size of your file), but for people with sluggish connections, it's imperative that you give them some kind of indication that everything is loading properly.

1. Create your preloader bar. For this example, I'll be drawing a basic rectangular bar that will expand within a thin border. Using the rectangle tool, set the stroke option in the Properties Panel to a hairline stroke, choose whatever fill color you want, make sure that Object Drawing mode is turned off on the toolbar, and draw your preloader rectangle in the center of the stage.

2. Separate the fill from the border. Since the border of the rectangle will stay constant while the fill expands within it, it will be easier if we send the fill to its own layer. To do this, simply hit Esc to make sure that everything is deselected, and then click once on the fill. Make sure that ONLY the fill is selected, and then right-click on the fill (or Ctrl+click if you're using a one-button mouse on a Mac) and click on Distribute to Layers. This will remove the fill from the current layer and copy to a new layer just below the current layer.

3. Convert the fill to a movie clip. Click on the fill (which should be on its own layer now) and hit F8 to convert it to a symbol. Select "movie clip" and set the registration point to the upper left corner. Our loader bar is going to be expanding from left to right, and this will only work properly if the registration point is on the left side. Give your movie clip an instance name of loader_mc.

4. Create a dynamic text field. This text field will tell the user what percentage of the site has loaded so far. For this example, select the Text Tool, choose Dynamic Text in the drop-down menu on the Properties Inspector, choose 12 point Verdana (or whatever font you want), and click and drag beneath your loader bar to draw a text field that has the same width as the loader. Here's what mine looks like:

dynamic text field

With this new text field selected, in your Properties Inspector, click on the button to right-align your text within the text field. Give this text field an instance name of loaded_txt.

5. Embed the font for the dynamic text field. Even if you select a popular font, such as Verdana, you can never be 100% certain that your users are all going to have the same font installed on their system. And when you're dealing with dynamic text fields, if your users don't have your selected font, and if you don't embed your font, then Flash will choose a different font to display, and you'll lose control of what your text fields look like.

To avoid this issue, select your dynamic text field, and then click on the "Embed" button in the Properties Inspector. In the pop-up dialog that appears, select Uppercase, Lowercase, Numerals, and Punctuation and click OK. To select more than one item, click on the top item, hold onto Shift, and then click on the bottom item. All items in between will be selected. Like so:

Embed options

6. Create a new keyframe for your content. You won't be able to test your preloader unless you actually have some content to load. So at this point, I want you to throw in a little bit of dummy content.

Create a new layer to hold your content, click on frame 2 for this new layer, and hit F6 to add a new keyframe. In this new keyframe, simply import a hi-resolution image or two onto the stage. This content does not have to be arranged in any sort of orderly fashion. You're just using this extra content to "fatten up" the file size so you'll have a way to test your preloader.

7. Add a stop action to frame 1. Since your Flash file now has 2 frames, you need to provide a way to keep the file from jumping back and forth between them. So add a new layer to the top of your layer stack, rename the layer Actions, click on frame 1 for the Actions layer, and hit Opt+F9 (or just F9 for PC) to open up your Actions panel. In your Actions, simply type stop();

8. Code the preloader. Make sure that frame 1 of the Actions layer is still selected, and add the following code to your script:

code

On lines 3 and 4, you're adding Event Listeners to the main timeline. The PROGRESS event handler on line 3 calls on the onProgress function over and over as long as content is still loading. The COMPLETE event handler calls on a function called onComplete and is triggered whenever the content has been fully loaded.

In the onProgress function, we first create a variable called loaded, which stores the number of bytes that have been loaded thus far and another variable called total, which stores the total number of bytes in the Flash file. When we divide loaded by total (line 10), we get the total percentage of the file that has currently been loaded, and we store it in a variable called pct. (Actually, it's technically a ratio instead of a percentage, but I won't be picky if you won't.)

We then use this pct variable (which, if everything is working properly, now contains a number between 0 and 1) to update the scaleX property of our loader bar movie clip. The scaleX property is basically the width of a movie clip as a ratio of its original width. So at this point, if your Flash file is 90% loaded, then the loader bar will be at 90% of its full width.

Once we have the width of the loader set, we then update the dynamic text field to tell our users precisely how much of our file has been loaded.

9. Test your movie. If everything is working properly, then when you test your movie (by hitting Cmd+Enter or Ctrl+Enter on PC), you won't see the preloader at all. It will jump straight to frame 2, where you have a hi-res image on the stage. This happens because when the file is already on your system, it is loaded immediately, and the COMPLETE event triggers the onComplete function to take us to the next frame of the Flash file. However, there is a way to simulate a download in order to test our preloader.

After hitting Cmd+Enter or Ctrl+Enter to test your movie, go to View > Bandwidth Profiler. This will display loading information above your movie. Once the Bandwidth Profiler is visible, go to View > Simulate Download. Hopefully, if all your ActionScript was entered properly, you will now see your preloader in action. As your loader bar expands to the right and your dynamic text field updates the percentage loaded, double-check this against the percentage that the Bandwidth Profilers says has been loaded. If these two numbers match, you're in business.

You can also adjust the speed of the simulated download by selecting View > Download Settings.

Once your Flash file finishes loading, you should see the preloader disappear and the next frame appear. And voila! You now have a fully-functioning preloader. Now all you need to do is replace the image(s) you stuck in frame 2 with the actual content of your website, and you're good to go!

Sample FLA file: preloader.zip

Tags: , , ,

77 Responses

  1. Khalil says:

    I replaced line 17
    nextFrame();
    with this one
    gotoAndPlay(2);
    and it works fine with flash movies

  2. Devyani says:

    When I test the movie, it remains blank for almost 50% of the movie load, the loader starts only after that. :(

  3. moodmaster says:

    Is there a way to have it only load a % then play…say 25%…as I just need to have it preload 2 embedded flvs at the front to load ….then it plays fine

  4. Jimbo says:

    What if you have a relatively complex preloader that’s counting up to 100%? I guess this bad-boy will have to go on the first frame. Do you then need to preload your preloader? Any ideas how you prevent that from appearing to start at say 30% rather than at 1%?

  5. Mary says:

    Has anyone had problems with this preloader in Firefox? It works fine in Safari, Explore and Chrome…but in Firefox the blue rectangle just appears. Is there something I am doing wrong? Check out the test link so you can see what I mean:

    http://www.okcorp.com/home_test_09.html

    Thanks…

  6. Elizabeth says:

    I was able to get the prloader for a hr pic working (thanx!) but after attempting to add an external swf with the use of some code from previous responses it failed miserably. I’m very new to flash could anyone tell me what is wrong with the code below…

    stop()

    this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
    this.loaderInfo.addEventListener(Event.COMPLETE, onComplete);

    function onProgress(e:ProgressEvent):void
    {
    var loaded:Number = e.target.bytesLoaded;
    var total:Number = e.target.bytesTotal;
    var pct:Number = loaded/total;
    loader_mc.scaleX = pct;
    loaded_txt.text = “Loading…” + (Math.round((pct * 100))+”%”);
    }

    function onComplete(e:Event):void{
    gotoAndPlay(2);
    var request:URLRequest = newURLRequest(“fa.swf”);
    var sida:Loader = new Loader();
    sida.load(request);

    sida.loaderInfo.addEventListener(Event.COMPLETE, onLoad);

    function onLoad(e).Event):void

    addChild(sida);
    sida.loaderInfo.removeEventListener(Event.COMPLETE, onLoad);
    }

    … any help would be greatly appreciated :)

  7. Pasacle says:

    is there a way to make it preload only 50% of total bytes and then start playing. i mean if the file is really huge and i don’t want the preloader to take forever…
    please if anyone can help!
    Thanks!

  8. Guy says:

    A very helpful tutorial, thanks

  9. Mareks says:

    Could somebody please point to as3 tutorial, where i can find a speedo dial preloader tutorial. Thanx in advance.

  10. Dave says:

    The preloader works fine, Thanks! However I have the same problem as some others on here, in my case it doesn’t start until 95%. I think the problem is that my content is in the library, and the stage is empty on frame 2. In the publish settings I’ve set “Export classes in frame: 2″ but I still get a long delay before the preloader starts. Is there a way to delay library loading until frame 2?

    Thanks!

  11. Dave says:

    Seems there is no easy way. Lee Brimelow has a tutorial on making a separate preloader because of the complexity of making a built in one:

    http://theflashblog.com/?p=438

  12. Nice ,Thanks For your Preloader Tutorials

  13. anthonyNigro says:

    im using flash Cs3 pro. when i try to test the movie, or simulate the download the script compilor error window pops up with two reports. there are syntax errors with the

    function onProgress(e:ProgressEvent):void

    on line 6. and another on the last line of scripting.
    is there anything i am doing wrong?

    stoneyo@sbcglobal.net

  14. Reed says:

    Very nice thanks for this toot.

  15. Sara, just put a “}” (rightbrace) before end of code (just read the error and do what it says!!).
    Dave, there’s no complexity in creating a built in preloader.
    Just check my stuff: http://bit.ly/CtVgv

  16. I n c r a d i b l e, in first time of my life, a preloader ready and functionally.

    Thx so much, save my month.

  17. Brett says:

    Craig,

    I am a Graphic Artist and have been now for roughly 10 years. I was trained at multiple schools for both fine arts and illustration all the way to extreme graphic arts like identity packages and such. Recently I learned that a large number of my clients were interested in new websites and web applications. These unfortunately were not in my knowledge base aside from basic dreamweaver knowledge.

    I would like you to know that I have spent the past few months learning flash as to better my understanding of interactive web design and you have been a major part. Aside from my learning curve (which is a big help) you have given me the knowledge needed to build myself as an artist. I have even been able to attract much more business due to this.

    Thank you very much and I would love to speak with you via eMail. Feel free to shoot me a message anytime. I can show you what I’m working on and maybe get some ideas. Thanks again.

    Brett Sanders
    KreAshun Studios

  18. Neeko says:

    Im having problems with the bar width animation. I need to have that bar in the main stage and the preloader has to be in a movieclip. so i figured if i ..

    MovieClip(parent).loadbar.scaleX = pct;

    ..if would work. but it’s not getting to the bar!
    any thoughs?? thanx in advance

  19. Sarah says:

    Hi, I’m practicing with this tutorial, and it’s very clear and easy to understand, unlike other tutorials I’ve tried to use. I’m very, very new to Flash(I just got it a week or two ago, and only know how to make buttons because they’re the easiest thing to do, in my opinion), and I wanted to make a flash movie, and of course you need a preloader, so I decided to make one. I got up to the Actionscript, and got an error saying “Access to undefined property” for lines 11 and 12. I, having no knowledge of Actionscript whatsoever(I must learn it…), am baffled. Any way to fix that?

  20. Sarah says:

    ^In addition to my previous comment, I test the preloader, and it flashes from the preloader to the pictures and back. I put in the Actionscript to stop that in the first line, but it still does it. I followed the steps to the letter, so I’m confused as to why this is happening. Any ideas?

  21. Arie says:

    I had the same problem that the preloader only started after 95%. I solved it by rightclicking in the library on my biggest movieclip containing most of the images. in the linkage menu I selected export for actionscript but.. and here is the mother.. deselected ‘Export in First Frame’!

    If you think about it, it makes sence.

  22. Web Worx says:

    Hi there, I just came across this AS3 preloader and must say it was easy to implement.

    My issue is with Firefox v3.5.3. When I refresh the page after the initial preload the site fails to load and only displays the preloader rectangle.

    This only occurs in FF, all other browsers are good. From what I gather it’s a cache issue, does anyone have any more insight on how to overcome this?

  23. Jon says:

    This solution does not work. I appreciate posting of information but I don’t really appreciate posting info that is slightly wrong. ( :

  24. Jafar says:

    yo this still worked for me, thanks for posting it

  25. Nuthman says:

    I have written a preloader that addresses a lot of random problems such as the annoying ‘stuck at 100%’ bug.. Check it out at http://www.as3blog.org/?p=6

  26. LInda says:

    HI Craig, I’ve done the preloader before my slideshowpro content (about 4MB). In the “test movie” it downloads frame “0″ which of course, has nothing in it and the preloader doesn’t appear until about 95% of the swf has downloaded. In the browers, the preloader doesn’t show up until it’s 95% done. Any way to have the preloader show up as soon as the page is clicked on? – at 0%? Been working at this for hours. Thanks in advance, Linda.

  27. Tracy says:

    I am having the same line 11 and 12 problem,(“Access to undefined property” for lines 11) I have no animation and the box appears immediately. Please can you help

    stop()

    this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
    this.loaderInfo.addEventListener(Event.COMPLETE, onComplete);

    function onProgress(e:ProgressEvent):void
    {
    var loaded:Number = e.target.bytesLoaded;
    var total:Number = e.target.bytesTotal;
    var pct:Number = loaded/total;
    loader_mc.scaleX = pct;
    loaded_txt.text = “Loading…” + (Math.round(pct * 100))+”%”;
    }

    function onComplete(e:Event):void
    {
    nextFrame();
    }

Leave a Reply