Creating a preloaded swf in haxe

Introduction


Since haxe 3 an empty first frame can be added to your main swf by using -D swf-preloader-frame.
Using this together with -swf-lib and -D flash-use-stage we can merge the main swf with a preloader swf. This will result in a final swf that has the preloader code in frame 1 and the assets and main code in frame 2, enabling us to monitor the loading of the swf.

Example

The directory structure for this example should look like this:

|- myproject
    |- application
        |- Application.hx
        |- image.jpg
    |- preloader
        |- Preloader.hx
     - build.hxml

build.hxml :
-main Application
-cp application
-swf-header 1024:768:30:FFFFFF
-swf application.swf

--next

Application
-cp application
-D swf-preloader-frame
-swf-header 1024:768:30:FFFFFF
-swf application/application.swc

--next

-main Preloader
-cp preloader
-D flash-use-stage
-swf-lib application/application.swc
-swf index.swf

Application.hx :
import flash.Lib;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;

@:bitmap('image.jpg')
class Image extends BitmapData {}

class Application extends Sprite
{
    public function new()
    {    
        super();
        var bmp = new Bitmap(new Image(0,0));
        addChild(bmp);
    }
    public static function main() 
    {
        Lib.current.addChild(new Application());
    }
}

Preloader.hx :
import flash.Lib;
import flash.display.Sprite;
import flash.events.Event;

class Preloader extends Sprite
{
    public function new()
    {
        super();
        addEventListener(Event.ENTER_FRAME, onLoadProgress );
    }
    function onLoadProgress(event:Event):Void
    {
        var bytesLoaded = Lib.current.stage.loaderInfo.bytesLoaded;
        var bytesTotal = Lib.current.stage.loaderInfo.bytesTotal;
        var percentLoaded = bytesLoaded / bytesTotal;
        trace("precentage loaded:" + Std.int( percentLoaded * 100 ) + "%" );
        if ( percentLoaded == 1 ) 
        {
            removeEventListener(Event.ENTER_FRAME, onLoadProgress );
            Lib.current.removeChild(this);
            var cls = Type.resolveClass("Application");
            var app = Type.createInstance(cls, []);
            Lib.current.addChild(app);
        }
    }
    public static function main() 
    {
        Lib.current.addChild(new Preloader());
    }
}

When you put the resulting index.swf online, you'll see the percentage of the swf that has been loaded in the trace output .
An additional application.swf is also created in case you want to run the swf without the preloader.

version #15873, modified 2013-01-30 13:31:48 by Antriel