Preloading unlimited numbers of images

var _xmlLoader:URLLoader = null;
var _xml:XML = null;    
var _counter:int = 0;    
var _list:Array = null;    
var _loader:Loader = null;    
var _imgList:Array = null;

function Init():void    
{     
    _xmlLoader = new URLLoader();     	
   _xmlLoader.load(new URLRequest("resources.xml"));
   _xmlLoader.addEventListener(Event.COMPLETE, Complete, false, 0, true);    
}        

function Complete($e:Event):void    
{     	
    _xmlLoader.removeEventListener(Event.COMPLETE, Complete);    	
    _xmlLoader = null;     	
    _xml = new XML($e.target.data);    
	    	
    _list = [];    	
    _imgList = [];    	
   _loader = new Loader();    	
    	 
   for(var i:int=0;i<_xml.image.length();i++)    	 
   {    		
        _list.push(_xml.image[i].@path);    	 
   }     	

    LoadImage();    
}        

function LoadImage():void    
{      
    _loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, Progress, false, 0 ,true); 
    _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ImageLoaded, false, 0 ,true);
   _loader.load(new URLRequest(_list[_counter]));    
}       

function Progress($e:ProgressEvent):void   
{      
    trace("Progress: " + (_counter+1).toString() + " / " +  (_xml.image.length()).toString() + " - " + (Math.ceil($e.bytesLoaded/$e.bytesTotal *100)).toString() + " %" );    
}        

function ImageLoaded($e:Event):void   
{     	
    _loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, Progress);     
    _loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, Complete);    	    	
    _imgList.push(new Sprite());    	
    _imgList[_imgList.length -1].addChild($e.target.content);  
   _loader.unload();     	
   _counter++;    	    	 
   if(_counter <= _xml.image.length() - 1)    	
  {    		
      LoadImage();    	 
   }else{    		
     _loader = null;    		
     _list = null;    		
     DisplayImages();    	 
   }         
}        

function DisplayImages():void    
{    	 
    for(var i:uint = 0; i&lt;_imgList.length;i++)    	
   {    	  
         addChild(_imgList[i]);    	 
    }    
}        

Init();

And this is how the XML should look like

   <?xml version="1.0" encoding="utf-8" ?> 
    <tutorial> 
    	<image path="images/image_1.jpg"/>
    	<image path="images/image_2.jpg"/>
    	<image path="images/image_3.jpg"/>
    </tutorial> 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s