[AS3] Creating Preloader for External swf in Flash ActionScript3

Tags:

When we load external swf files in Flash Movies, they may take some time to load and it’s better to place a preloader in the main movie to inform user that content is loading. It’s a bit tricky to set up preloader for external swf using ActionScript3 in Flash.

Following example will show how you can load external swf file, create a preloader and show it before displaying the loaded swf file to the user:

 
function launchSWF(vBox, vFile):void{	
 
var swfLoader:Loader = new Loader();
 
var swfURL:URLRequest = new URLRequest(vFile);
 
swfLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressHandler);
swfLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadProdComplete);
 
swfLoader.load(swfURL);
 
function loadProdComplete(e:Event):void {
	trace("swf file loaded");	
	//remove the preloader from container clip
            vBox.removeChild(preLoader);
 
           // add the loaded swf to container clip
	vBox.addChild(swfLoader);	
 
	currentSWF = MovieClip(swfLoader.content);
	currentSWF.gotoAndPlay(1);
 
	currentSWF.addEventListener(Event.ENTER_FRAME , checkLastFrame);
 
function checkLastFrame(e:Event):void {	
 
if (currentSWF.currentFrame == currentSWF.totalFrames) {
     currentSWF.stop();
    // trace("stopped");     
   }
 
   }   
 
}
 
var preLoader:loader = new loader();
 
//position the loading bar
preLoader.x = 155;
preLoader.y = 185;
 
vBox.addChild(preLoader);
 
function onProgressHandler(event:ProgressEvent){
 
var dataAmountLoaded:Number=event.bytesLoaded/event.bytesTotal*100;
preLoader.bar.scaleX = dataAmountLoaded/100;
preLoader.lpc.text= int(dataAmountLoaded)+"%";
 
trace(preLoader.bar.scaleX );
 
   }	
 
}
 
//create the container clip
var container:MovieClip = new MovieClip();
 
//define the swf file to load
var swfFile:String = 'external-file.swf';
 
//define a MovieClip to store current swf ref
var currentSWF:MovieClip = new MovieClip();
 
//call the function to load swf, provide container clip and external file
launchSWF(container, swfFile);
 
//put it on stage
addChild(container);

You can download this functional external swf preloader fla file from here.

Hope that helps.

Cheers!

Related posts:

  1. [AS3] Loading External SWF into MovieClip using Loader Class in Flash ActionScript3
  2. Multiple External SWF Slideshow – Loading & Playing Mupltiple External SWFs in AS3 Flash Movie
  3. [AS3] Load External swf into Main Flash Movie with Play, Pause, Forward, Rewind, Load and Unload Buttons
  4. External SWF Player with Play, Pause, Forward, Rewind Buttons and Seek Bar
  5. [AS3] Load External swf into MovieClip & Play/Pause/Forward/Rewind and Stop it at LastFrame from Main Flash Movie