Building a Preloader with ActionScript 3 using mxmlc and the Frame Pragma

Wed, 23 Sep 2009

Good news: 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 this:

1. put this before the definition of your main class:

[Frame(factoryClass="myPackage.MyPreloadClass")]

The code above tells the mxmlc to take the given (custom) class under myPackage.MyPreloadClass and use it as a Preloader (there is some more background info about the Frame-pragma on the adobe-blog).

2. Write your preloader-class, extending the MovieClip-Class (since you need something with frames and sprites don’t have them). See bit-101 for an example-class.

3. That’s it. Er … well, not completely, since if you need to load some other stuff, say for example depending on a CMS-generated XML-File, the path to which is handed to your swf using flashvars, you will no longer get the the flashvars with

LoaderInfo(mainClass.root.loaderInfo).parameters

but with

LoaderInfo(preloader.root.loaderInfo).parameters

where “preloader” is a reference to the preloader-instance – that’s why I am passing a reference to the Preloader as a parameter when instantiating my main class.

5. Now your preloader would still think everything is ready, once the swf is completely loaded. That’s not the case, since you still lack the stuff defined by your on-the-fly-cms-generated XML.

My solution is to pass my main class a callback-function as another parameter, which tells the preloader when the loading is really done.

In principle the passing of a preloader-reference to the main class would suffice, but then the function triggering the end of the loader-animation would have to be defined public …