Preloader without a loader-swf in AS3
Here’s one method of loading your AS3 movie, using a preloader class that loads before all other classes.
The flex compiler can actually split up the code for you so one class loads before all others. Even though we’re using the flex compiler to do this we do not have to have a Flex project, it can be a Flash project or a pure actionscript project. If we’re using a Flash project we do have to set the flex compiler path though.
Anyways, the way it works is that in your main class you add the Frame metadata, like this:
package com.flassari { // Preloader meta tag [Frame(factoryClass="com.flassari.Preloader")] // Start of our own application code [SWF(backgroundColor="#FFFFFF", frameRate="24", width="800", height="600", pageTitle="My preloaded project")] public class Main extends Sprite {
The preloader has to extend movieClip, because behind the scenes it is using frames for its magic.
In your preloader class, when it is done loading (by checking if it is at the last frame), your have to instantiate the main class with no strict typing. If you were to use strict typing, the whole application would have to load before the preloader can be shown so that would defeat the purpose of a preloader:
private function onEnterFrame(e:Event):void { if (currentFrame == totalFrames) { // If we're at the frame where Main is ready // Stop and clean up stop(); removeEventListener(Event.ENTER_FRAME, onEnterFrame); // Create the main application and add it to the display list var mainClass:Class = getDefinitionByName("com.flassari.Main") as Class; addChild(new mainClass() as DisplayObject); } }
Just remember, everything that the preloader references will be loaded before the preloader can be shown, so keep it to a minimum.
Also, because the main class is created before it is put on the stage, be sure not to reference the stage in the constructor.
Tags: AS3, class, factory, factoryclass, Flash, flex sdk, frame, loader-swf, preloader, single swf, swf
February 10th, 2011 at 14:03
cool, i think that is is also used in the default preloader template in flashdevelop, but never really understood how it works, thanks!
September 25th, 2012 at 23:51
MANY thanks man, I was eating my heart out trying to get it to work until you mentioned “Just remember, everything that the preloader references will be loaded before the preloader can be shown, so keep it to a minimum.”. I was referencing my main movie for a type checking… so it was loading the entire thing before showing the preloader. You saved my life! :D