21st January 2007

Preloaders in AS3

posted in Brevity, Flash |

[Note, although this post is right now over a year and a half old, it continues to be one of the most visited pages on my site. If you are just showing up here now, you should note that the data here is a bit dated and may not work exactly as described in the current version of the Flex SDK. In fact, I am pretty sure it DOESN'T work as described anymore. Feel free to read through this for some overall info, but check all the comments as well, which may have more info or links to more up-to-date data. I haven't had to deal with this situation since I first wrote this, so don't have the current method for making AS3 preloaders to hand.]

It's an age old problem. Let's go back to AS2: You have a relatively large SWF, consisting of exported movie clips in the library, and/or a good deal of code contained in classes. All classes and exported assets load in prior to frame one being displayed, so the viewer sees nothing while it is all loading in.

Solution: Turn off "export first frame" on your exported assets, and place an instance on some frame in the timeline to force them to be compiled into the SWF. For classes, set classes to export to some later frame. Then put your preloader on frame one, stop the timeline, loop until everything is loaded, then jump to an initialization frame.

Now jump to AS3 with mxmlc. There is no timeline. Embedded assets and all classes load in prior to frame one as in a default IDE-created SWF. So, how do you create a preloader?

Well, if you are using Flex, it's all programmed in there for you, and while I don't know the specifics, I know you can specify a custom preloader in Flex, and there is obviously a default preloader in a Flex app. Since the Flex framework is all written in AS3, I knew there must be some way to do this in an AS3 only project, but it wasn't very clear. In fact, you might say it was rather hidden. My first idea was to check the compiler arguments. These two seemed interesting:

frames.frame label class name [...]
Specifies a SWF file frame label with a sequence of class names that are linked onto the frame.
This is an advanced option.

generate-frame-loader=true|false
Toggles the generation of an IFlexBootstrap-derived loader class.
This is an advanced option.

But that is the entire extent of the documentation on the subject, and doing a web search didn't turn up a whole lot more.

Then, last Thursday, Ted Patrick happened to be in Boston, and stopped by for a tour of Brightcove. We were sitting there talking to Brian Deitte, who was also part of the Flex team til a few months ago and it occurred to me that one of these guys must have the answer. They pointed me to the [Frame] metadata tag, and said to check out the source for mx.core.Application. Sure enough, I see the following:

/**
* The frameworks must be initialized by SystemManager.
* This factoryClass will be automatically subclassed by any
* MXML applications that don't explicitly specify a different
* factoryClass.
*/
[Frame(factoryClass="mx.managers.SystemManager")]

And, checking out SystemManager, I see a few interesting tidbits:

// NOTE: Minimize the non-Flash classes you import here.
// Any dependencies of SystemManager have to load in frame 1,
// before the preloader, or anything else, can be displayed.

and

* The SystemManager is the first display class created within an application.
* It is responsible for creating an mx.preloaders.Preloader that displays and
* mx.preloaders.DownloadProgressBar while the application finishes loading,
* then creates the mx.core.Application instance.

And finally, the create() method, which is basically called when the movie is fully loaded in:

Actionscript:
  1. public function create(... params):Object
  2. {
  3. var mainClassName:String = info()["mainClassName"];
  4.  
  5. if (mainClassName == null)
  6. {
  7. var url:String = loaderInfo.loaderURL;
  8. var dot:int = url.lastIndexOf(".");
  9. var slash:int = url.lastIndexOf("/");
  10. mainClassName = url.substring(slash + 1, dot);
  11. }
  12.  
  13. var mainClass:Class = Class(getDefinitionByName(mainClassName));
  14. return mainClass ? new mainClass() : null;
  15. }

A bit more searching around led me to this post by Roger Gonzalez, which explains it a bit more, though highly oriented towards Flex. Even he describes the Frame tag as "semi-secret and bizarre". :) He also mentions that it is basically an inline alias for the "frames" compiler configuration option. So, with a bit more work I could probably figure out how to do it that way, but the metadata way seems easier so far.

This was enough for me to start testing in AS3 only. Here's the deal:

First you create your main class as usual, and point the compiler to that as the class to compile.

You then use the [Frame] metadata tag, passing in another class as the factoryClass, like so:

[Frame(factoryClass="MyFactoryClass")]

This is where the magic happens. Basically, the Frame tag forces the compiler to create a two-frame SWF. All of your embedded assets, your main class and any classes that are used by the main class are forced into frame two. The only thing that goes into frame one is your specified factory class and any classes or embedded assets that it uses. Hence the above warning to include minimal other classes in this class.

So, this factory class is where you create your preloader. Generally, you want to stop the timeline, and then set up an enterFrame listener, or a timer to check currentFrame against totalFrames. When they are equal, it means that the rest of your classes and assets are loaded in and ready to go. You then want to call nextFrame() to move to frame two so those classes and assets will be available. At that point, you can instantiate your main class, using getDefinitionByName(). This allows your factory class to create a new instance of the main class without compiling a reference to that class into it - which would force the main class and everything else to load in frame one and defeat your preloader.

The slightly weird thing about this setup is that you are usually used to your main class being the "document class". That is, the main class represents the main timeline of the SWF. In this setup though, the factory class actually becomes the document class. This has a few ramifications:

  1. The factory class has to extend MovieClip. NOT Sprite! It actually has frames, so it should be a MovieClip.
  2. When you create an instance of your main class, you then have to do an addChild to get it onto the display list.
  3. Your main class will not be the at the base of the display list. It will be a child of your factory class.
  4. Because you instantiate your main class, and THEN add it to the display list, be careful not to have its constructor call code which will refer to stage, as its stage property will not be available until after it is added.

OK, let's look at an example. First we have the main class, which we will target with mxmlc:

Actionscript:
  1. package {
  2. import flash.display.Sprite;
  3. import flash.display.Bitmap;
  4.  
  5. [Frame(factoryClass="com.bit101.MyFactory")]
  6. public class FrameTest extends Sprite
  7. {
  8. [Embed(source="big_asset.jpg")]
  9. private var Asset:Class;
  10.  
  11. public function FrameTest()
  12. {
  13. init();
  14. }
  15.  
  16. public function init():void
  17. {
  18. var asset:Bitmap = new Asset();
  19. addChild(asset);
  20. }
  21. }
  22. }

This doesn't do much other than embed a large jpeg image, which makes the SWF come in at over 3 MB. If you were to compile this normally, the end viewer would see a blank screen until that jpeg fully loaded in. But the addition of the line:

[Frame(factoryClass="com.bit101.MyFactory")]

causes the main class, along with the embedded jpeg, to go into frame two. Note that in this case it is safe for the the constructor to call the init function directly. But, as mentioned earlier, you might want to delay that until the instance is actually added to the display list, to avoid null stage references, etc.

Now let's look at the factory class:

Actionscript:
  1. package com.bit101
  2. {
  3. import flash.display.DisplayObject;
  4. import flash.display.MovieClip;
  5. import flash.display.StageAlign;
  6. import flash.display.StageScaleMode;
  7. import flash.events.Event;
  8. import flash.utils.getDefinitionByName;
  9.  
  10. public class MyFactory extends MovieClip
  11. {
  12. public function MyFactory()
  13. {
  14. stop();
  15. stage.scaleMode = StageScaleMode.NO_SCALE;
  16. stage.align = StageAlign.TOP_LEFT;
  17. addEventListener(Event.ENTER_FRAME, onEnterFrame);
  18. }
  19.  
  20. public function onEnterFrame(event:Event):void
  21. {
  22. graphics.clear();
  23. if(framesLoaded == totalFrames)
  24. {
  25. removeEventListener(Event.ENTER_FRAME, onEnterFrame);
  26. nextFrame();
  27. init();
  28. }
  29. else
  30. {
  31. var percent:Number = root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal;
  32. graphics.beginFill(0);
  33. graphics.drawRect(0, stage.stageHeight / 2 - 10,
  34. stage.stageWidth * percent, 20);
  35. graphics.endFill();
  36. }
  37. }
  38.  
  39. private function init():void
  40. {
  41. var mainClass:Class = Class(getDefinitionByName("FrameTest"));
  42. if(mainClass)
  43. {
  44. var app:Object = new mainClass();
  45. addChild(app as DisplayObject);
  46. }
  47. }
  48. }
  49. }

Note that it extends MovieClip. It immediately stops the timeline and adds an enterFrame listener. In that handler, it checks to see if framesLoaded == totalFrames. If so, it calls nextFrame() to make the main class available, and then calls init, which gets a reference to the main class, instantiates it, and adds it to the display list.

While second frame is still loading, it simply draws a progress bar on the stage, using root.loaderInfo.bytesLoaded and root.loaderInfo.bytesTotal to access the percent loaded.

This is a pretty simple example, but shows you how it works. I'm pretty sure it's the only documentation out there on how to do this in AS3, so feel free to share it around.

Post to Twitter

This entry was posted on Sunday, January 21st, 2007 at 12:21 pm and is filed under Brevity, Flash. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

There are currently 100 responses to “Preloaders in AS3”

  1. 1 On January 21st, 2007, Tink said:

    Nice handy find!

  2. 2 On January 21st, 2007, Grant Skinner said:

    Good post Keith. Thanks.

  3. 3 On January 21st, 2007, sascha/hdrs said:

    Keith to the rescue! I take it you have read my comment posted lasted week! I’ve also tried the compiler arguments but as Flex doesn’t need them I thought there must be another way. However the stuff with the factory class was confusing me and the docs are not help at all in this case. Thanks for this great explanation! btw is -generate-frame-loader deprecated? It doesn’t appear in the compiler arguments list when using mxmlc -help advanced. Just wondering.

  4. 4 On January 22nd, 2007, The Lazy FlashDev » Blog Archive » BIT-101 Blog » Blog Archive » Preloaders in AS3 said:

    [...] BIT-101 Blog » Blog Archive » Preloaders in AS3 [...]

  5. 5 On January 22nd, 2007, William from Lagos said:

    Great Keith. And thanks for sharing.

    BTW, I’m loving your book (3 Cookbook), so much!

  6. 6 On January 22nd, 2007, Ash said:

    Bookmark’d!

  7. 7 On January 22nd, 2007, andy makely said:

    This works great! Thanks!

    How is it that the getDefinitionByName(“FrameTest”) is able to resolve the class? Usually it throws an error if the desired class has no previous reference…

  8. 8 On January 23rd, 2007, sascha/hdrs said:

    Tried it, works great but I get one odd thing with this approach: A ‘Default CSS file not found’ warning. Any ideas why this is happening? I never got this warning in an AS project before.

  9. 9 On January 27th, 2007, liuhuan said:

    Really useful, thanks a lot!!!

  10. 10 On January 30th, 2007, actionscript cheatsheet - blog: actionscript news, tips, tutorials » ActionScript 3.0 Quick Start said:

    [...] Preloaders in AS3 http://www.bit-101.com/blog/?p=946 [...]

  11. 11 On February 4th, 2007, Den Ivanov said:

    Very nice article. Thanx. Who know how many “semi-secret and bizarre” they have in their pockets? ))))

  12. 12 On March 5th, 2007, Nathan de Vries said:

    Sascha/hdrs: You’re using a Flex component without defining your Application in MXML, right? The MXML compilation process auto-generates a bunch of code, including that style class you’re missing. When a Flex component is initialized, it expects those auto-generated classes to exist, but they won’t if you’ve written your application in AS3 (no MXML).

    The only way around this (AFAIK) is to define your base Application class in MXML, and then load in your AS3 classes on creationComplete. Either that, or don’t use Flex components :) .

  13. 13 On April 26th, 2007, boostworthyisryantaylor » AS3 Metadata Tags said:

    [...] Keith Peters posted a really detailed write-up of how to use this tag for preloading a few months ago. Basically, the deal is that you can use this tag to force the compiler to create a two-frame SWF file. ActionScript: [...]

  14. 14 On May 11th, 2007, sascha/hdrs said:

    Nathan thanks but I also get this warning even though I don’t use a single Flex2 component in my app. The odd thing is that the warnings will even double and triple after a while of compiling. So I get 2 or 3 of the same warning.

  15. 15 On May 22nd, 2007, Austin Haas said:

    getDefinitionByName() was throwing an error for me, but simply importing my main class and changing init() to:
    private function init():void{
    var app:Object = new MyMainClass();
    addChild(app as DisplayObject);
    }

    worked fine.

  16. 16 On May 23rd, 2007, Austin Haas said:

    Crap. Scratch my last comment. By using the class name directly, instead of getDefinitionByName, I was causing the class and all of it’s dependencies to be loaded from the start, bypassing the whole purpose of the preloader.

    I got the getDefinitionByName() to work by adding the package name onto the quoted class name. I don’t know if that has something to do with my mxmlc compile command or what.

  17. 17 On May 24th, 2007, ej said:

    thanks for the useful information.

    when i try this though, the size of my app jumps from 80k to 190k. I even stripped your preloader class down to basically nothing, importing just movieclip, displayobject, and event.

    also interesting, when i remove the frame command, and just import the preloader class into the Main class it does not jump to 190k.

    so im guessing flash imports a bunch of flex stuff when you add the frame command?? is there any way to find whats getting imported or stop this?

  18. 18 On June 27th, 2007, Bart said:

    Thanks for the post. It helped my to make a good preloader.

    You mentioned that I cannot refer to the stage in my main class. So, can you give me a hint on how to make a stage listener then, i still hope this is possible?

    Thanks for any reactions

  19. 19 On June 30th, 2007, Kris said:

    This code works fine for me…

    package {

    import flash.display.Sprite;
    import flash.display.Bitmap;
    import flash.events.Event;

    [Frame(factoryClass="com.bit101.MyFactory")]

    public class FrameTest extends Sprite {

    [Embed(source="big_asset.jpg")]
    private var Asset:Class;

    public function FrameTest() {
    addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }

    public function onEnterFrame(event:Event):void {
    // if root != null then the Factory Class is loaded and you can use stage
    if (root != null) {
    removeEventListener(Event.ENTER_FRAME, onEnterFrame);
    init();
    }
    }

    public function init():void
    {
    var asset:Bitmap = new Asset();
    addChild(asset);
    asset.x = (stage.stageWidth – asset.width) / 2;
    asset.y = (stage.stageHeight – asset.height) / 2;
    }
    }
    }

  20. 20 On July 3rd, 2007, RT said:

    Does this apply to swf’s created in the Flash CS3 authoring environment, or some other form of actionscript 3.0 coding? It’s hard to believe this is the way to get a progress bar to load before all other content in an swf. Why can’t the developers of Flash just create a straight forward way to accomplish such an essential task?

  21. 21 On July 9th, 2007, Tink said:

    @RT

    No this is for ActionScript 3.0 projects created with Flex Builder not Flash CS3.

    In Flash you can just place all your assets on frame 2 of your main timeline just like you could in previous versions of Flash.

  22. 22 On July 9th, 2007, Tink said:

    @Bart and Kris

    You can listen for Event.ADDED_TO_STAGE

  23. 23 On July 10th, 2007, Tink said:

    “Your main class will not be the at the base of the display list. It will be a child of your factory class.”

    I’ve just implement this method in a project (as you can see I was looking at this post last night) and decided to add the main class to the display list of the preloaders parent i.e.

    private function create():void
    {
    var MainClass:Class = Class(getDefinitionByName( “MainClass” ) );
    var mainClass: DisplayObject = new MainClass();
    parent.addChild( mainClass );

    parent.removeChild( this );
    }

    Doesn’t seem to cause any problems but I also get the warning “Default CSS file not found” (in fact i have it twice), and this is a pure AS 3.0 application (i.e. no Flex).

  24. 24 On August 1st, 2007, DeceptiveResolution said:

    Here’s something i made for Flash CS3:
    http://deceptiveresolution.wordpress.com/2007/08/01/flash-cs3-preloading-stage-assets-external-classes-is-this-a-useful-hack/

    I thought it might be relevant to this thread. Any suggestions will be greatly appreciated.

    Regards

  25. 25 On August 8th, 2007, sascha/hdrs said:

    Just found out today that just by simply putting something like [Frame(factoryClass=”com.bit101.MyFactory”)] before your class makes the resulting SWF approx. 130Kb large. Anyone else who can confirm this? 130Kb are usually a bit too much for a preloader so this renders this method for a preloader rather useless!

  26. 26 On August 8th, 2007, kp said:

    it shouldn’t add that much. sounds like you are getting some flex stuff into your factory. you gotta make sure you really limit what you access in that class.

  27. 27 On August 8th, 2007, sascha/hdrs said:

    Keith, I’ve tried it. I’ve made a basic class and as soon as I add [Frame(factoryClass=”… the SWF becomes 130Kb. First I though it’s because of my preloader class which also uses some other classes. But I’ve commented out all related stuff and even without it and only the [Frame… line before the class it results in 130Kb.

  28. 28 On August 22nd, 2007, Al Lemieux said:

    Thanks for doing this!!! I pared down your example to its strict basics and got it to work. One question: what’s the benefit of registering the movie clips in the class as opposed to having Flash automatically detect them?

  29. 29 On August 22nd, 2007, Al Lemieux said:

    I’m getting an error only when I test at DSL or T1 speeds. It doesn’t happen at 56k. Here’s the error:

    TypeError: Error #1009: Cannot access a property or method of a null object reference.

    The preloader works and when it’s complete it takes me to the correct frame, which has a stop action. I’m wondering if the enterFrame event isn’t being properly removed?

  30. 30 On September 11th, 2007, FlexMerge » Preloaders in AS3 said:

    [...] BIT-101 Blog comments [...]

  31. 31 On September 17th, 2007, Francis Gabon said:

    Thanks for that soooo useful tip :) It’s a shape that there is no relevant doc about those compiler options.

    Nevertheless, I got the same errors as Al and Sascha: my SWF is now 130kb bigger, and when testing bandwidth with Sloppy Java applet, I got the TypeError #1009. Any clues about that, Keith?

  32. 32 On September 17th, 2007, Francis Gabon said:

    erratum: “it’s a SHAME…” :p

  33. 33 On September 26th, 2007, kris said:

    My swf-file is 4.4K when compiling with flex 2 (eclipse plugin). I tried compiling the same source with mxmlc (flex2sdk) and the swf-file is 129K !!!???

  34. 34 On October 1st, 2007, kris said:

    This mxmlc compiler option solved the problem :

    -verbose-stacktraces=false

  35. 35 On October 4th, 2007, Frameメタデータタグ | blog by dynalogue said:

    [...] http://www.bit-101.com/blog/?p=946 [...]

  36. 36 On October 10th, 2007, eka said:

    I try this, and works , but i cant see the bar … is like it’s loading everything before even start in frame 1

    any clue?

  37. 37 On October 12th, 2007, Matthias said:

    Hello Keith,

    I found recently also the Frame meta tags when compiling an MXML based project using -keep compiler option and I came across the following meta tags:
    [Frame(extraClass="_CustomPreloader_FlexInit")]
    [Frame(factoryClass="_CustomPreloader_mx_managers_SystemManager")]

    I also found these interesting lines in the Flex Framework that are related to this topic:

    sdks\2.0.1\frameworks\source\mx\core\FlexModuleFactory.as (94): addFrameScript(docFrame, docFrameHandler);
    sdks\2.0.1\frameworks\source\mx\core\FlexModuleFactory.as (94): addFrameScript(docFrame, docFrameHandler);
    sdks\2.0.1\frameworks\source\mx\core\FlexModuleFactory.as (94): addFrameScript(docFrame, docFrameHandler);
    sdks\2.0.1\frameworks\source\mx\core\FlexModuleFactory.as (96): // Frame 1: module factory
    sdks\2.0.1\frameworks\source\mx\core\FlexModuleFactory.as (97): // Frame 2: document class
    sdks\2.0.1\frameworks\source\mx\core\FlexModuleFactory.as (98): // Frame 3+: extra classes

    So my questions here are:
    * Do you know when to use “[Frame(extraClass=”?
    * Is the document/main class really on Frame 1 and the Factory on Frame 2?
    * Why do I still get the “Default CSS file not found” warning? I don’t want to use the Flex Framework in one of my AS3 only projects, so I need no Default CSS or the like..

    Matthias

  38. 38 On October 12th, 2007, Koali blog » Blog Archive » Preloading in an AS3 only project said:

    [...] Keith peiters has a wonderful tutorial on how to preload in an AS3 only project. I had been wondering myself but had just been cheating and having my as3 app sitting in a flex app. [...]

  39. 39 On October 12th, 2007, eka said:

    Hi all
    i found out that It’s working… thanks, but i get a yellow frame like focus that when i click it disappear… or when doing tab… i tried with focusRect = null etc… and still there… any clue?

  40. 40 On October 13th, 2007, AS3 Prelaoder at flash und so… said:

    [...] Wenn man mit Flex arbeitet muss man sich um den Preloader icht kümmern. Wie man aber selbst einen Preloader erstellt, wenn man nur ein reines AS-Projekt hat wird hier beschrieben. Search [...]

  41. 41 On October 15th, 2007, baec said:

    Hi Keith and all,

    Thanks, super help. Worked. Cleaned lotsa things up. I also get the “no default CSS” warning.
    One question though, just cant figure it out …

    in the flex SystemManager create method you have posted above there is the line -


    var mainClassName:String = info()["mainClassName"];

    further down in that SsytemManager class i found a very cryptic -


    public function info():Object
    {
    return {};
    }

    so where does that info object get populated ? that bit allows them to have a generic system manager and only send it a different main class name. but how can they set that info before anything loads ?
    the only thing i can think of is that it has something to do with the flex compiler since i have noticed the info object contains other tags for stuff set as compiler options or mxml settings ( backgroundColor etc ) ?! anyone ?

    ~:(

  42. 42 On October 17th, 2007, RubenDoliveira said:

    Hi all,

    I’m getting this error, what I’m doing wrong?

    ReferenceError: Error #1065: Variable FrameTest is not defined.
    at global/flash.utils::getDefinitionByName()
    at classes::preloader/::init()
    at classes::preloader/onEnterFrame()

  43. 43 On October 23rd, 2007, H7 said:

    AS 3.0 is very poorly documented in my opinion. I am glad this works for you, but I have no idea on how to test it… I suppose it would be nicer if this kind of tutorials would be more beginner oriented…

  44. 44 On October 29th, 2007, pedro said:

    Thank you, you just saved me a lot of fiddling :)

  45. 45 On November 7th, 2007, sascha/hdrs said:

    Kris: “This mxmlc compiler option solved the problem : -verbose-stacktraces=false”

    … Kris this is not working for me. No matter what I do it always add up ~110Kb when I use this preloader method. Any other ideas why the file size gets so bloated?

  46. 46 On November 7th, 2007, erixtekila said:

    TIP :
    If you want to save a bunch a bytes in your generated swf code, beware of using the flex.swc and utilities.swf as library (-library-path)
    WARNING : There seems to have a subtle difference between the flex2 and flex3 command line option :
    -compiler.library-path alias for flex2 is -l
    -compiler.library-path alias for flex3 is -library-path

    Maybe the weight problem of sascha/hdrs…
    HTH

  47. 47 On November 8th, 2007, sascha/hdrs said:

    Thanks erixtekila! Yes I have found this out yesterday (see here http://www.actionscript.org/forums/showthread.php3?t=152148 ). It’s just strange that the Flex stuff gets included even though it is not really reffered in the compiled code.

  48. 48 On November 11th, 2007, roflmao said:

    i get the same error as RubenDoliveira is flash cs3…
    Austin Haas has solved it somehow, but i can’t get it running. somebody can help me please?

  49. 49 On November 13th, 2007, erixtekila said:

    You’re welcome, Sascha !
    I use a different setting than the url you’ve posted.
    Note that mine work with the last release of flex 3 beta 2.

    I keep playerglobals.swc as an external-lib (like you can see in the Adobe’s flex-config.xml) and set the complete path to utilities.swc and flex.swc
    That way only the depencies of the flex framework are bundled in the swf. The weight comes from that side if you check in the swf bytecode.
    See you in the FDT forum ;)

  50. 50 On November 20th, 2007, nulldesign - personal portfolio and flash experiment corner of lars gerckens » Preloader in AS3 projects (factoryClass) said:

    [...] The last days I was playing around with the Flex Metadata Tag “Frame” to implement a preloader in an AS3 project. You might have read Keith Peters post concerning this issue. This method is working fine, except of the fact that I can’t get rid of the flex framework classes in my compiled SWF, which blows up the size of an nearly empty SWF to 120kb. If you check out the comments in his post, you’ll find a few solutions, but none of them worked for me. So I generated a XML exclude File, that excludes the whole flex framework. You might want to give it a try: flex_framework_exclude.xml (compile with the option -load-externs+=flex_framework_exclude.xml). It’s still not satisfying, but it’s working… [...]

  51. 51 On November 30th, 2007, nulldesign - personal portfolio and flash experiment corner of lars gerckens » AS3 Preloading continued said:

    [...] The class “Test” acts as the factory class that’s responsible for the preloading. The Class “Demo” is the main application class. Using the compiler option -frame frameLabel Demo, the class Demo is compiled into frame 2. Just like in Keith Peter’s Example and my try using and exclude xml, you can preload a pure AS3 application now, but in this case no flex framework classes are compiled into the resulting SWF and there is no need for an exclude xml. Finally! [...]

  52. 52 On December 5th, 2007, Akewea said:

    Wonderful !

    It’s just what i was looking for ! :)

    Thanks for all ! I thing I’ll put a quick French translation on my blog, if you agree.

    Akewea

  53. 53 On December 27th, 2007, jawele said:

    first of all thx for the tutorial!

    I’m sure there must be a way to do it without screw up the “root” object….

  54. 54 On January 14th, 2008, Roxie said:

    http://cargo-trailers.acworthauto.in/ cargo trailers

  55. 55 On January 23rd, 2008, Scott said:

    I found a way to get rid of that annoying “default css file not found” warning. I’m still not sure why it even happens, but if you put a file called “default.css” in the same directory as your main .as file, and then set the following compiler option it works:

    defaults-css-url “default.css”

    I used to get another warning added to the list every time I compiled like many others had mentioned, but now it seems to be gone for good! My default.css file is empty BTW.

  56. 56 On February 5th, 2008, Ed said:

    For anyone getting a ReferenceError: Error #1065: Variable [some variable] is not defined

    Make sure you’re specifying your main class (the one containing “[frame(factoryClass=...]“) as the compile target — NOT the preloader class.

    That frame metadata tag instructs the compiler to look up the specified class automatically.

  57. 57 On February 5th, 2008, Ed said:

    Found a simpler solution on http://www.nulldesign.de/2007/11/30/as3-preloading-continued/

    The following is copied directly from that page:

    “I wasn’t really satisfied with the solution I used for my AS3 preloader (see post: Preloader in AS3 projects). Now Sven found THE solution. It’s in german, so I try to explain how it works:

    “The class “Test” acts as the factory class that’s responsible for the preloading. The Class “Demo” is the main application class. Using the compiler option -frame frameLabel Demo, the class Demo is compiled into frame 2.

    “Just like in Keith Peter’s Example and my try using an exclude xml, you can preload a pure AS3 application now, but in this case no flex framework classes are compiled into the resulting SWF and there is no need for an exclude xml. Finally!”

  58. 58 On February 24th, 2008, RevPatricia Walker said:

    Can you help me with a preloader on this http://www.alphachurch.org/worshipg1tough.htm I’m in the dark on as3 and need a visual example to proceed, if you have time to help me. Thanks, Patricia

  59. 59 On February 27th, 2008, Ruy Adorno said:

    Great solution! And the comments have a lot of good stuff too! Keep’on with the good work!

  60. 60 On March 10th, 2008, Markus said:

    I am working with Flex Builder 3 Beta and when i tried out the to put the [Frame… tag in my code, then i get the following errors:

    - Unable to resolve resource bundle “core” for locale “en_US”
    - Unable to resolve resource bundle “effects” for locale “en_US”
    - Unable to resolve resource bundle “skins” for locale “en_US”
    - Unable to resolve resource bundle “styles” for locale “en_US”

    I don’t even know what is the meaning of “locale”?!?
    Please help

  61. 61 On March 25th, 2008, Writing a preloader in ActionScript 3 | Jetpack Development said:

    [...] is German, but the source code is readable). Also thanks to Lars Gerckens for his research, and BIT-101 for this alternate solution. And of course thanks to Adobe for providing such horrendously incomplete documentation that things [...]

  62. 62 On March 25th, 2008, Adept said:

    I wrote up a description of another way to to this here: http://www.jetpackhq.com/blog/2008/03/25/writing-a-preloader-in-actionscript-3/

    However I’m running into another problem: in a web browser, not standalone, bytesTotal appears to represent the total bytes in the first frame, rather than the total bytes in the SWF. Any ideas?

  63. 63 On March 26th, 2008, Adept said:

    From looking at the source code to mx.preloaders.DownloadProgressBar, Adobe’s own code actually has to guess at the size of the SWF it’s loading. Weak. So no “percentage loaded” indicator is going to be accurate unless you explicitly provide it with the estimated size of your SWF. :(

  64. 64 On April 1st, 2008, newton said:

    would you tell me how i can do this preloading in document class in flash, i fear about the extra 110 kb of flex that load up even if i do nothing, so i need a work around in flash it self.

  65. 65 On April 13th, 2008, Chris said:

    How does this show a progress bar? It only updates the progress on Event.ENTER_FRAME, which only happens once.

    Btw, I think this guy plagiarized you: http://www.dreaminginflash.com/2007/11/13/actionscript-3-preloader/#comment-274

  66. 66 On May 14th, 2008, Chris said:

    Weird, upgraded to the Flex 3 SDK on Linux, and now ENTER_FRAME is called repeatedly, as it’s supposed to.

  67. 67 On June 12th, 2008, rgnbgn.de » Blog Archive » Preloader für ActionScript 3 said:

    [...] If you stumbled upon this page but don’t understand German, a good starting point for you is Preloaders in AS3 by Keith [...]

  68. 68 On June 27th, 2008, Zir0 said:

    Hey.

    I made a simple code as you have here, but my percentage is always 100%, throughout the entire duration of the preloader.

    When I trace bytesLoaded and bytesTotal, it turns out that bytesTotal is always the same value as BytesLoaded, and BOTH numbers are reflecting the number of bytes loaded. :-/

    Any ideas?

  69. 69 On July 7th, 2008, ac said:

    for my testing of keith’s code above, the result is same as what Zir0 observed.
    frame 1 and frame 2 always loaded together at the same time.
    framesLoaded == totalFrames always true,
    and bytesTotal is always the same value as BytesLoaded.

    my development tool is only flex_sdk_3’s mxmlc.exe.
    my testing environment is: IE6, win2k, flash10.ocx.

    which development tools are you guys using?
    any idea?
    thx.

  70. 70 On July 16th, 2008, marc said:

    Error #1065: Variable [some variable] is not defined.
    metadata is not for flash IDE, it will be ignored.

  71. 71 On August 31st, 2008, Mauft.com Games » Mario not yet. said:

    [...] before next Sunday. Though, I have managed to make a pure AS3 preloader for the game, thanks to This post on Bit-101 Blog. Other than that… Ah yes, I’ve been working for two days on a little, [...]

  72. 72 On September 6th, 2008, blog.xperiments.es » Blog Archive » AS3 Only Preloaders said:

    [...] http://www.bit-101.com/blog/?p=946 [...]

  73. 73 On September 18th, 2008, Flash tutorials | Preloader Roundup | Lemlinh.com said:

    [...] Read more [...]

  74. 74 On September 23rd, 2008, Elden Randolph said:

    Your site is about the only thing I’ve been able to find to offer guidance on this subject. Thank you for creating the web site. I hope you can help direct me toward additional information and/or places where I can find more of this info.

  75. 75 On October 5th, 2008, gamepoetry » The Last Preloader You’ll Ever Need said:

    [...] AS3 only preloader is heavily borrowed from the one described at bit-101. If you’re interested in the technical reasons for why this preloader works, then I would [...]

  76. 76 On October 13th, 2008, UVE Producers Team » Blog Archive » Precargas en Flex said:

    [...] Este post es una adaptación traducida al castellano de un post de bit-101. [...]

  77. 77 On October 15th, 2008, Kaleb Wyman said:

    @Those with the “Default CSS not found” error message.

    Not sure if this is recommended, but if you open up the .actionscriptProperties and comment out…

    such as…
    <!—->

    …this stops the “default css file not found” error message as well.

  78. 78 On December 7th, 2008, 积件网 » Blog Archive » AS3 Metadata Tags (转) said:

    [...] Keith Peters posted a really detailed write-up of how to use this tag for preloading a few months ago. Basically, the deal is that you can use this tag to force the compiler to create a two-frame SWF file. [...]

  79. 79 On January 11th, 2009, Preloaders in AS3 | Bonashen.com said:

    [...] 源文出处:http://www.bit-101.com/blog/?p=946 [...]

  80. 80 On February 9th, 2009, wangkang said:

    there is an alternative solution for those projects not built by FlexBuilder:

    http://www.ghost23.de/blogarchive/2008/04/as3-application-1.html

  81. 81 On February 12th, 2009, Drus’ blog, my stuff. » Blog Archive » Precargas en Flex said:

    [...] Este post es una adaptación traducida al castellano, a petición del público, del método que nos muestran en este post de bit-101. [...]

  82. 82 On February 19th, 2009, Larry said:

    can we use

    stage.addChild(app as DisplayObject);

    at line 45 in factory class?

    I think this makes the “display tree” more clear and independent.

  83. 83 On February 23rd, 2009, felix said:

    Been using this method for a while now with no problems. However I just observered a bug when using it with swfaddress 2.2. For some reason the preloader does not show when deeplinking into a page. Loading the main URL (with no #) shows the preloader as usual.

  84. 84 On February 23rd, 2009, felix said:

    regarding my comment above – just found the solution here: http://sourceforge.net/forum/message.php?msg_id=5057312

  85. 85 On March 16th, 2009, Workflow Flex / Flash CS4 para actionscript projects (II) | blog.arturoparacuellos.com said:

    [...] lo más importante cómo hacer la precarga del proyecto sin usar el Metatag Frame, (método originario de Mike Chambers) ya que esto impide que desde CS4 compile bien. En este caso me baso en este [...]

  86. 86 On June 22nd, 2009, Preloading in an Actionscript Only Project « dynamicClass said:

    [...] working in an Actionscript Only Project without having to include any of the flex project. Bit 101 http://www.bit-101.com/blog/?p=946 has a post about using the frame metatag but unfortunately all my attempts to use it resulted in at [...]

  87. 87 On June 28th, 2009, Link Dump Sunday (June 28th, 2009) - Porter’s World said:

    [...] to OOP: A nice introduction to explaining the basics of Object Oriented Programming. 5.) Pre-loaders with AS3: One developers take on how to implement a pre-loader using AS3 (often an annoying [...]

  88. 88 On July 7th, 2009, Flex Custom Preloader — blog.andrewpb.com said:

    [...] This is a pretty simple example but I hope it shows you how it works. Aside from my solution, I found a few articles on the topic, with the most promising being this one from Ted on Flex. [...]

  89. 89 On July 29th, 2009, Erik said:

    Any good references or suggestions how to load in RSLs with this spproach?

  90. 90 On August 11th, 2009, Geraint said:

    Anyone know why this would not work in firefox but be fine in IE?

    Thanks for your time
    Geraint

  91. 91 On August 20th, 2009, achidutsu said:

    To Erik
    Any good references or suggestions how to load in RSLs with this spproach?

    package com.netBrothers.service
    {
    import flash.display.DisplayObject;
    import flash.display.Loader;
    import flash.display.MovieClip;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.URLRequest;
    import flash.system.ApplicationDomain;
    import flash.system.LoaderContext;
    import flash.utils.getDefinitionByName;

    public class appLoader extends MovieClip
    {
    // Массив адресов библиотек
    protected var libs:Array;
    // Индекс текущей библиотеки для загрузки
    protected var libsLoadIndex:Number;
    // Loader для загрузки библиотек
    public var libLoader:Loader;
    // Имя класса основного приложения
    protected var mainApplicationClassName:String;

    // Запишем время старта и окончания загрузок
    protected var preloaderInitTime:Number;
    protected var loadAppCompleteTime:Number;
    protected var loadLibsCompleteTime:Number;

    public function appLoader(libs:Array, mainApplicationClassName:String)
    {
    preloaderInitTime =
    (new Date()).getTime();

    this.libs = libs;
    this.mainApplicationClassName =
    mainApplicationClassName;
    libsLoadIndex = 0;

    // Инициализируем загрузчик
    libLoader = new Loader();
    libLoader.contentLoaderInfo.addEventListener(Event.INIT, libLoaderInitHandler);
    libLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, libLoaderErrorHandler);
    libLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, libLoaderErrorHandler);

    stop();
    stage.scaleMode = StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP;
    addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }

    // Вызывается при окончании загрузки .swf файла
    // главного приложения
    protected function init():void
    {
    nextFrame();
    var mainClass:Class = Class(getDefinitionByName(mainApplicationClassName));
    if (mainClass)
    {
    var app:Object = new mainClass();
    addChild(app as DisplayObject);
    }
    }

    // Начинает загрузку библиотек
    public function loadLibs():void
    {
    loadAppCompleteTime = (new Date()).getTime();
    if (libs && libs.length > 0)
    loadLib();
    else
    libsLoaded();
    }

    // Загрузка текущей (libsLoadIndex) библиотеки
    protected function loadLib():void
    {
    var urlRequest:URLRequest = new URLRequest(libs[libsLoadIndex]);
    var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
    libLoader.load(urlRequest, loaderContext);
    }

    protected function libsLoaded():void
    {
    loadLibsCompleteTime = (new Date()).getTime();
    init();
    }

    // event handlers

    protected function libLoaderInitHandler(event:Event):void
    {
    libsLoadIndex++;
    if (libsLoadIndex == libs.length)
    libsLoaded();
    else
    loadLib();
    }

    protected function libLoaderErrorHandler(event:Event):void
    {
    trace(“libLoaderErrorHandler: ” + event);
    }

    public function onEnterFrame(event:Event):void
    {
    graphics.clear();
    if(framesLoaded == totalFrames)
    {
    removeEventListener
    (Event.ENTER_FRAME, onEnterFrame);
    loadLibs();
    }
    else
    {
    var percent:Number = root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal;
    graphics.beginFill(0);
    graphics.drawRect(0, stage.stageHeight / 2 – 10, stage.stageWidth * percent, 20);
    graphics.endFill();
    }
    }
    }
    }

  92. 92 On August 23rd, 2009, shaman4d said:

    Thank you, its very usefull solution. Could you please explain what different among it and -frame start (option compiller) solution? Sad but workaround with “Default CSS file not found” problem spend little more time for project setup.

  93. 93 On August 24th, 2009, christian said:

    A bit disappointing the file gets 36kb bigger, despite there are not assets or external classes imported in the factory class. But definitely a very handy technique. Thanks!

  94. 94 On September 23rd, 2009, Building a Preloader with ActionsScript 3 using mxmlc and the Frame Pragma - drewing.de said:

    [...] you really don’t need the timeline to build a preloader. The technique is described in detail at bit-101. In short it works like [...]

  95. 95 On October 18th, 2009, Visual Harmonics » Post Topic » AS3 game multi-frame preloading using mxmlc / no Flash IDE said:

    [...] Peters’ recommended this method for those who are using mxmlc (usually via Eclipse/FDT or FlashDevelop) to compile their code. I [...]

  96. 96 On October 18th, 2009, Nick Wiggill said:

    For those looking for the solution to the getDefinitionByName() problems, and realised they couldn’t use a reference to class or they’d defeat the whole purpose of the preloader, look no further:

    1. Import your main application class in your factoryClass with a normal import statement.

    2. To ensure the import statement is not optimised out by the compiler (due to it not being referenced in the normal way), go and change your mxmlc compiler options, using the following additional switch to force the import you created above:

    -includes=com.mysite.Main

    And ensure, of course, that that same class is imported in

    Many, many thanks go to Matthias Eichstedt over at Mike Chambers’ blog ( http://www.mikechambers.com/blog/2006/06/22/actionscript-3-get-a-class-reference-by-class-name/ ) for pointing this out. And of course to Keith for digging this grand solution out of the minds of the Adobe guys :)

  97. 97 On October 18th, 2009, Nick Wiggill said:

    Oops, please ignore the line in my above post that says, “And ensure, of course, that that same class is imported in” — that was just cruft I forgot to delete. 1 and 2 are the only steps needed to get this working.

  98. 98 On October 21st, 2009, Tamas Gronas said:

    It works! Thank you!

  99. 99 On November 26th, 2009, Replacing ENTER_FRAME at AlecMcE.com said:

    [...] the two event dispatcher methods could be attached. I remembered reading in an excellent article by Bit 101 how using a [Frame] metadata tag would force your application to have two frames. This seemed to be [...]

  100. 100 On November 26th, 2009, Alec McEachran said:

    I have another use for the [Frame] Metadata Tag which may be of interest: http://alecmce.com/as3/replacing-enter_frame

    The solution was inspired by a memory of this post – many thanks.

Leave a Reply

Who is reading BIT-101?

Copyright ©2009 by Keith Peters. All rights reserved. This means that you may not reprint or repost the contents of this site without express written permission of the author.


  • Calendar

  • February 2010
    M T W T F S S
    « Jan    
    1234567
    891011121314
    15161718192021
    22232425262728
hoodia order buy Levitra Plus betablockers weight loss information buy pills without a prescription arthritis menopause ambien doses cat's eye health information on cholesterol cialis online order valtrex cheapest phentermine onlin e increase breast size lower blood sugar immediately terramycin which is better cialis or viagra buy cheap cialis reduce cholesterol naturally new blood pressure treatment products for back pain cheapest cialis index will levitra help piroxicam 20 mg order viagra online in germany buy tadalafil online buy levitra onlines how to naturally lower cholesterol buy generic viagra where to buy soma anti allergic drug levothyroxine dogs new hair loss treatmen buy levitra pain meds buy cheap malaria therapy weight loss after baby asthma medications chronic snoring viagra gel prostate cancer cures order viagra cialis alprazolam men health natural cure arthritis immune system support diet medicine cialis approval lipitor effects where can i buy arthritis drugs overactive bladder in men self help weight loss natural cholesterol control ativan medication cialis approval best cure for snoring breast enhancing pills order prozac celebrex pharmacy buy levitra onlines premature ejaculation cure confidence hypnotherapy free stop smoking bust enhance diet weight loss supplements skin fungal infection valium with no prescription viagra with out prescription breast enhancement products alpha blocker medications azithromycin 250mg skin disease chronic heart failure medicines dog care products buying cialis online gerd in children antibiotics to buy my drug store muscle building diet drugs affecting levitra anti anxiety medications really large breast enhancement help for constipation ulcers stomach drugs for high blood pressure selling pet products buy pain medicine viagra online overnight fucidin ointment generic zyrtec prices soft tab cialis smoking treatment dog products online weight loss solution cialis on line blue pills weight loss diet pill nitroglycerin sublingual floxin prevention of heart attack imuran order gasex vermox treatment of depression Viagra On Line buy generic cialis professional tooth whitening kits to buy valium 2mg treatment for hypertension ultram cheapest online stores hair loss products cheap weight loss diovan prescription malaria preventative taurine treating prostate cancer immune system support natural constipation cure phentermine no prescription fast delivery purchase meds without prescription buy plendil diet drug taking viagra after cialis protonix cheapest generic cialis online viagra levitra cialis yohimbe benefits muscle mass gain diet and health products medical treatment for insomnia buy blood pressure meds buy celexa levaquin interactions blood pressure drug skin disorder where can i buy arthritis drugs natural breast enhancer acute pain control online diazepam natural acne remedy antifungal strategies triphala pravachol online how can i stop smoking breast enhancement natural nautral breast enhancement beta blocker medications wellbutrin dosages order viagra cialis lower high blood pressure mass muscle phentermine from canada how to loss weight osteoporosis bone health lipitor use dog medication drug allergies buy diazepam buyviagra cialis phentermine 37.5 mg zestril medication parkinsons treatment generic revatio free nexium cosmetic dentistry tooth whitening avalide generic buy cheap tadalafil uk simvastatin tablets buy cialis online in usa breast pain cat care ovulating clomid medical skin care lines viagra to canada viagra or cialis cheap cialis tramadole buy azulfidine drugs used for cancer ear pain oral ketoconazole raloxifene evista taurine sex with levitra stop smoking today heart failure natural cholesterol control protonix dose oxybutynin 5mg irritable bowel syndrome treatments new treatment for hepatitis c cheap prescription drugs viagra online prescription depression therapy buy sumycin menopause treatment hair loss treatments medication pletal what is a natural antibiotic viagra purchase synthroid tablets generic prilosec lipitor cat health info discount vitamin cholesterol and health bacterial diarrhea weight loss medicine new treatment for depression removing retention fluids diuretic medicines soma 250mg cat anxiety loss weight online pharmacy viagra buy phentermine without a prescription herbs for breast growth cymbalta dosage fast weight loss supplement arthritis menopause levitra online order cheapest place to buy phentermine cold flu medications for nausea buy ultram where pills for acne free weight loss programs help with anxiety improve skin valium 2mg urinary tract health cat urinary tract disease crestor dosage drug zofran calan zyrtec buy nirdosh dosage digoxin buy pain patch acomplia alendronate cialis best price cheap wellbutrin small dog products depression medicine sildenafil dosage dog health depression and anxiety lamictal withdrawal viagra, levitra and cialis online drug buy bone maker strontium cures for hair loss nitroglycerin tablets natural arthritis treatment arimidex buy buy energy patch how to treat a yeast infection viagra herb alternative viagra cialis levitra order sublingual cialis cialis comparison breast lift augmentation seroquel for depression carisoprodol mg new treatment for depression cialis soft tabs safe sleep aid severe leg muscle pain natural weight loss gabapentin medication what is ambien clozapine medication viagra online ordering cures for hair loss free weight loss help buy viagra levitra pet treats order plan b diabetes type 2 phentermine risk ultram er side effects treatment for hepatitis b constipation cures drugs used in treating depression leg pain buy cheap generic cialis anti anxiety meds hypnotherapy for weight loss motilium body building fitness dog skin relieve upper back pain cures for high blood pressure cardura celecoxib Viagra Online Cheap cheap bactrim ambien online lamisil cost infertility meds progesterone clomid osteoporosis hormon urinary tract infection symptoms hypnotherapy for health how to buy viagra online joint pain cure online allegra buy generic cialis uk generic abilify cures for lung cancer new treatments for lung diseases pain meds buy cheap treatment for dry skin disease of the skin nexium drug free stop smoking buy tooth whitening products viagra tablet naprosyn dosage women's fertility male sexual power carisoprodol purchase asthma attack treatment estradiol pills phentermine from canada pet health care hair loss products online astelin generic cheap estrace free weight loss program buy rimonabant relieve lower back pain lexapro prescription new breast cancer drug buying ambien best online viagra scams home scabies treatment hair loss in woman buy generic cialis uk eye drop gabapentin medication amitriptyline uses ultram no prescription natural pain cures buy cla products back pain lowest price generic viagra pain meds buy cheap mg buy phentermine acne skin care cialis rx weight loss and fitness nitrofurantoin buy phentermine without a prescription high blood pressure medicines stop hair loss viagra china use levitra female health coreg dosage carisoprodol price pain relief product breast enlargement depression pills buy how to treat flu home neck pain relief order imitrex online vitamin b-6 cialis soft tabs pharmacy software description of soma buy isoniazid cheap prevacid help ear infections on dog fat burning stop smoking remedies rhinitis treatment chronic pain relief birth control online meds without prescriptions buy lovastatin drug stores penis enlargement without pill cancer medicine buy deltasone cure for throat infection thyroid dogs dosage cipro viagra from uk cheap alcoholism treatment natural cure for constipation paxil cialis 5mg tablets amitriptyline uses topamax drugs lower heart rate drug discount codes dog medicines body fat loss joint pain recurring urinary tract infections ativan information buy drugs online cheap fast valium body building ambien maximum dosage information on valium how to sperm more chlamydia medication dosage buy cialis online viagra chest pain heart fluconazole interaction calcium channel blocker side effects zolpidem dosage online drug stores zelnorm muscle strength fluconazole buy stress gum free weight loss products information on gout low immune system online viagra cialis 20 buy cefixime phentermine from canada gain muscle mass fast lasix side effects buy singulair penis enlargement free natural muscle and joint health viagra online overnight cialis online aceon allergies and asthma diamox side effects weight loss software generic compazine price for tramadol high blood pressure symtoms osteoporosis help treatment severe constipation drug new smoking stop pain relief product xanax online dog health info clonazepam .5mg buy tribulus pregnancy prevention methods allergy hives