Preload This!

Creating a Preloader in AS3

Creating a preloader in AS3 is pretty straight forward and really should be used any time your pulling resources into an SWF at runtime and yes I know the title is stupid.

There are a few steps involved so lets go one step at a time – be sure to import the appropriate class packages along the way.

Step 1 – Create an instance of the Loader class.

import flash.net.Loader;
var _loader:Loader = new Loader();

Step 2  – Create a URLRequest for the object you want to load making sure to pass the Url as a string

import flash.display.Loader;
 import flash.net.URLRequest;
var _loader:Loader = new Loader();
 var _itemToLoad:URLRequest = new URLRequest("URL TO YOUR OBJECT HERE");

Step 3 – Add EventListeners to the Loader object and define the handlers for them

import flash.display.Loader;
 import flash.net.URLRequest;
 import flash.events.Event;
 import flash.events.ProgressEvent;
var _loader:Loader = new Loader();
var _itemToLoad:URLRequest = new URLRequest("URL TO YOUR OBJECT HERE")
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progress_handler);
 _loader.contentLoaderInfo.addEventListener(Event.COMPLETE,load_complete_handler);
  
function progress_handler(e:ProgressEvent):void
 {
var _bytesLoaded:Number = e.bytesLoaded;
 var _bytesTotal:Number = e.bytesTotal;
 var _percentLoaded:Number = Math.round((_bytesLoaded/_bytesTotal)*100);
 trace (_percentLoaded)
}
function load_complete_handler(e:Event):void
 {
trace("load complete");
 addChild(_loader);
}

Step 4 – Initiate the load.

import flash.display.Loader;
 import flash.net.URLRequest;
 import flash.events.Event;
 import flash.events.ProgressEvent;
//create a loader object
 var _loader:Loader = new Loader();
 //create a urlrequest for the object you're loading
 var _itemToLoad:URLRequest = new URLRequest("http://lesstroud.ca/wp-content/uploads/2010/09/500x_survivorman.jpg")
//add event listeners to loader object
 _loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progress_handler);
 _loader.contentLoaderInfo.addEventListener(Event.COMPLETE,load_complete_handler);
 //define event handler function
function progress_handler(e:ProgressEvent):void
 {
var _bytesLoaded:Number = e.bytesLoaded;
 var _bytesTotal:Number = e.bytesTotal;
 var _percentLoaded:Number = Math.round((_bytesLoaded/_bytesTotal)*100);
 trace (_percentLoaded)
}
function load_complete_handler(e:Event):void
 {
trace("load complete");
 //add element to the stage
 addChild(_loader);
}
//start the load
 _loader.load(_itemToLoad);

When you publish the file, you should see the percent loaded updating in the Output panel.

A real-world application would be to update a text field with the percent value (converted to a string of course).

Once the object is finished loading the Event.COMPLETE event is fired and the load_complete_handler adds the object to the stage.

Leave a Reply

Your email address will not be published. Required fields are marked *