AS3 | Flash | Tutorial

How to build an Object-Oriented ActionScript 3 Preloader in Flash CS4: 2 Methods

The magic of creating a preloader in ActionScript 3 lies in the LoaderInfo class. Every instantiated DisplayObject instance (all objects that appear on the stage, plus the stage itself) have a loaderInfo property that returns a LoaderInfo instance that contains information about the loading progress of that particular display object. Creating a preloader for the whole application is a matter of monitoring these LoaderInfo instances.

Method 1: Monitor Stage LoaderInfo instance

Under this method the loading progress is monitored via the LoaderInfo instance associated with the stage. Since all assets that will appear in the application need to be attached to the stage, the stage’s LoaderInfo instance will reflect the loading of all these assets.

Graphics

  1. Go to File → New… and select Flash File (ActionScript 3.0).
  2. Using the Rectangle tool create a rectangle (include a stroke) on the stage that is 100 pixels wide by 10 pixels high.
  3. Click on the fill of the newly created rectangle and select Modify → Convert to Symbol… Name the new instance ProgBar and set the registration point to left-middle. This will be the progress bar of the preloader.

    preloader_pbar

  4. With the new ProgBar instance selected on the stage, go to the Properties panel and name the instance progBar.
  5. Select the whole rectangle (stroke and progress bar instance). Select Modify → Convert to Symbol… Name the new instance Preloader and set the registration point to left-middle. Check the Export for ActionScript button.
  6. Click OK. If you get a warning that says the “definition for this class could not be found” click OK again.
  7. With the new Preloader instance selected, go to the Properties panel and name the newly created instance preloader. Your library should look like the following:

    preloader_library

  8. Select frame 2 of the main timeline, go to Insert → Timeline → Blank Keyframe. All content for the application will appear on frame 2 and beyond.
  9. Go to Insert → New Symbol… Name the new instance Content. If you check Export for ActionScript be sure to uncheck Export in frame 1, otherwise the preloader will not function properly.
  10. Place all content of the application on the timeline of the newly created Content instance.
  11. Return to the main timeline. Select frame 2 and drag an instance of the Content symbol from the library and place it on the stage.
  12. In the Properties panel of the stage name the document class Main. If you get a warning that says the “definition for this class could not be found” click OK.

    preloader_docclass

  13. Save the file.

Code

  1. Go to File → New… and select ActionScript File.
  2. Paste the following code and save the file as Preloader.as in the same directory as the .fla file saved earlier.
    package
    {
    	import flash.display.Sprite;
    	import flash.display.LoaderInfo;
    	import flash.events.Event;
     
    	public class Preloader extends Sprite
    	{
    		/**
    		* Alias for stage LoaderInfo instance
    		*/
    		private var _targetLoaderInfo:LoaderInfo;
     
    		/**
    		* The percent loaded
    		*/
    		private var _loadPercent:Number = 0;
     
    		/**
    		* Constructor
    		* Listen for when the preloader has been added to the stage 
    		* so that the progress of the remaining load can be monitored.
    		*/
    		public function Preloader()
    		{
    			this.addEventListener( Event.ADDED_TO_STAGE , _init );
    		}
     
    		/**
    		* Initialize variables.
    		* Set initial width of the progress bar to 0 
    		* and listen for enter frame event.
    		*/
    		private function _init(evt:Event):void
    		{
    			_targetLoaderInfo = stage.loaderInfo;
     
    			progBar.scaleX = 0;
     
    			this.removeEventListener( Event.ADDED_TO_STAGE , _init );
    			this.addEventListener(Event.ENTER_FRAME, _onCheckLoaded);
    		}
     
    		/**
    		* Check the status of the load, once complete dispatch a complete event.
    		*/
    		private function _onCheckLoaded(evt:Event):void 
    		{
    			_loadPercent = _targetLoaderInfo.bytesLoaded / _targetLoaderInfo.bytesTotal;
    			progBar.scaleX = _loadPercent;
    			if (progBar.scaleX == 1)
    			{
    				this.removeEventListener(Event.ENTER_FRAME, _onCheckLoaded);
    				this.dispatchEvent( new Event(Event.COMPLETE) );
    			}
    		}
    	}	
    }
  3. Go to File → New… and select ActionScript File a second time.
  4. Paste the following code and save the file as Main.as in the same directory as the .fla file saved earlier.
    package 
    {
    	import flash.display.MovieClip;
    	import flash.events.Event;
     
    	public class Main extends MovieClip 
    	{
    		/**
    		* Constructor
    		* Stop timeline and add event listener to preloader.
    		*/
    		public function Main() 
    		{
    			this.stop();
    			preloader.addEventListener( Event.COMPLETE , _initContent );
    		}
     
    		/**
    		* Load has finished, remove preloader and preceed to next frame.
    		*/
    		private function _initContent(evt:Event):void 
    		{
    			preloader.removeEventListener( Event.COMPLETE , _initContent );
    			this.removeChild(preloader);
    			nextFrame();
    		}
    	}
    }
  5. To test the preloader go to Control → Test Movie. Go to View → Simulate Download.
  6. Download method 1 complete source

Method 2: Monitor content SWF LoaderInfo instance

Under this method two SWFs are created, one encapsulating the preloader and the other encapsulating all content. The content SWF is loaded inside of the preloader SWF, which monitors the loading progress.

Graphics

  1. Follow steps 1 – 7 in the previous method.
  2. In the Properties panel of the stage name the document class PreloaderWrapper. If you get a warning that says the “definition for this class could not be found” click OK.
  3. Save the file.
  4. Go to File → New… and select Flash File (ActionScript 3.0).
  5. Add the content for your application to the timeline of this file.
  6. Save the file as content.fla.
  7. Go to Control → Test Movie to create the content.swf that will be loaded by the preloader SWF.

Code

  1. Go to File → New… and select ActionScript File.
  2. Paste the following code and save the file as PreloaderWrapper.as in the same directory as the .fla file saved earlier.
    package 
    {
    	import flash.display.Sprite;
    	import flash.display.Loader;
    	import flash.display.LoaderInfo;
    	import flash.display.DisplayObject;
    	import flash.events.Event;
    	import flash.events.ProgressEvent;
    	import flash.net.URLRequest;
     
    	public class PreloaderWrapper extends Sprite 
    	{
    		/**
    		* Alias for content LoaderInfo instance
    		*/
    		private var _targetLoaderInfo:LoaderInfo;
     
    		/**
    		* The percent loaded
    		*/
    		private var _loadPercent:Number = 0;
     
    		/**
    		* Constructor
    		* Creates Loader instance, adds event listeners and begins loading content SWF.
    		*/
    		public function PreloaderWrapper() 
    		{
    			var loader:Loader = new Loader();
    			_targetLoaderInfo = loader.contentLoaderInfo;
    			_targetLoaderInfo.addEventListener( ProgressEvent.PROGRESS, _loadingData );
    			_targetLoaderInfo.addEventListener( Event.COMPLETE , _finishedLoading );
    			loader.load( new URLRequest("content.swf") );
     
    		}
     
    		/**
    		* Monitor loading progress and update progress bar.
    		*/
    		private function _loadingData( evt:ProgressEvent ):void 
    		{
    			_loadPercent = _targetLoaderInfo.bytesLoaded / _targetLoaderInfo.bytesTotal;
    			preloader.progBar.scaleX = _loadPercent;	
    		}
     
    		/**
    		* Remove event listeners and preloader, and attach content SWF to stage.
    		*/
    		private function _finishedLoading( evt:Event ):void 
    		{
    			_targetLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, _loadingData );
    			_targetLoaderInfo.removeEventListener( Event.COMPLETE , _finishedLoading );
    			this.removeChild(preloader);
    			this.addChild( DisplayObject(LoaderInfo(evt.target).content) );
    		}
    	}
    }
  3. To test the preloader go to Control → Test Movie. Go to View → Simulate Download.
  4. Download method 2 complete source

UPDATE July 30, 2009: I noticed I forgot the private designation on two of the methods in the PreloaderWrapper class. They have been added.