In ActionScrirpt 3.0 the way to load external media content like images or .swf files is to use the Loader class. The instance of this class is a DisplayObject too (actually a DisplayObjectContainer) which loads the content inside it and has to be added to display list to be viewed, just like any other DisplayObject.
The way you have to load the external content is a little bit different in AS3 using the Loader class than in AS2, using the well known MovieClip.loadMovie() method or loadMovieNum(). It resembles more on using the MovieClipLoader class from AS2.
Here is an example. If you want to load an image called flower.jpg and display it, here’s what you have to do:
- - create the loader object:
var loaderObject:Loader = new Loader(); - - set the coordinates:
loaderObject.x = 150;
loaderObject.y = 45; - - add the loader to the display list:
addChild(loaderObject);
At this point, anything you load inside it will be visible on the stage. If you would load the content without adding the loader object to the stage, there wouldn’t be anything displayed until the addChild() method call.
- - you need to create a URLRequest object which is based on the URL of the content itself:
var request:URLRequest = new URLRequest("flower.jpg"); - - now you can instruct the Loader instance to load the image:
loaderObject.load(request);
You could use a shortcut and combine the previous two lines into a single line of code:
loaderObject.load(new URLRequest("flower.jpg"));
Sometimes the content you want to load has a larger size than the stage or the area where you want to display it. So, you’ll have to resize the loader. Doing it write after the load() method call would result in not displaying anything, even if the content has been successfully loaded. This is because the loader gets resized after the load() method but before the content gets fully loaded (especially if it has a larger file size).
The solution for this problem is to always resize the Loader object after the content has completely loaded. To do this, you need to listen for the event the loader dispatches when it finishes loading the content: Event.COMPLETE:
loaderObject.contentLoaderInfo.addEventListener(Event.COMPLETE, resizeLoader);
function resizeLoader(evtObj:Event):void {
loaderObject.width = 400;
loaderObject.height = 300;
}


