One of the first issues you'll encounter when migrating from AS2 is that you cannot place any AS3 code on the timeline. All AS3 code lives in external class files. The next thing that will cross your mind is this:

"If you can't place code on the timeline and you can't use an AS3 class until it's loaded in, how the hell do you write a preloader?"

If you work with Flex then this isn't your problem - the compiler will take care of preloading for you. If you work with Flash CS3 you'll need to get used to a few new ways of working.

The Document class
FLA files for an AS3 project can have a root document class. This is the equivalent of using Linkage to associate a class with a library item, but in this case you are linking a class to the Stage. This class is immediately available and in most cases you will use it to preload the rest of the SWF.

Garbage collection
One thing missing from most preloader solutions I've found is garbage collection. This is a really big deal in AS3. Grant Skinner covered it much better than I ever could in a series of posts about AS3 Resource Management. One of the best ways to remember to do this is to always write a destroy() function alongside your constructor. This function should remove any listeners you may have set up during the life of the class.

MainPreloader.as
The code below contains only the bare essentials required to get your preloader working. In the next post I'll show you an easy way to customise the look of your preloader.

package 
{
  import flash.display.StageAlign;
  import flash.display.StageScaleMode; 
  import flash.display.MovieClip; 
  import flash.events.*; 
    
   public class MainPreloader extends MovieClip 
   {
      public function MainPreloader():void 
      { 
        super(); 
        init(); 
      } 
    	
      protected function init():void 
      { 
        stop();
        this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, onMainLoadProgress); 
        stage.scaleMode = StageScaleMode.NO_SCALE; 
        stage.align = StageAlign.TOP_LEFT;
      }

      protected function destroy():void {
        this.loaderInfo.removeEventListener(ProgressEvent.PROGRESS, onMainLoadProgress); 
      } 
        
      protected function onMainLoadProgress(e:ProgressEvent):void 
      { 
        var percent:Number = Math.round((e.bytesLoaded / e.bytesTotal )*100 ); 
        preloader.gotoAndStop( percent ); 
        trace(percent + "% loaded"); 
        if (e.bytesLoaded == e.bytesTotal )
        { 
          onMainLoaded() 
        }; 
      } 
            
      protected function onMainLoaded():void 
      {
        destroy(); 
        play(); 
      }
   }
}