How To Load an Image at Runtime in AS3 and Display Load Progress

In this simple example, we show how to use the Loader class to load an image
at runtime. We show how to instantiate the Loader class, add all the necessary listeners,
and display load progress. We happen to load a jpeg file, but you can use the same code to load
an external swf file.

We load an image called space2.jpg. The image file is located
in the same directory as the fla file for the applet, htimgload.fla, but more importantly, the image file will
be located in the same directory on the server as the swf and html files
corresponding to this applet. That is why, within 'doLoad' function,
we pass the local address "space2.jpg" to the URLRequest. If the file is not
in the same directory, you pass the corresponding local address of your image file
on your server to the URLRequest. Loading from remote domains may cause
Flash Player security errors. We do not try to catch security errors
in this How-To.

In htimgload.fla, we created on the Stage some static text and a dynamic TextField
with the instance name 'infoBox'. In this field, we display
messages to the user about loading. We also created on the Stage
a button with the instance name 'btnLoad'.

Now, on to the code. We create an instance of the AS3 Loader class
and store the instance in a variable called, in our case,
'loader'. The simplest way to add loaded content to the Display List,
is to add 'loader' itself to the Display List. We make it
a child of the MainTimeline ('this' stands for the MainTimeline.)

var loader:Loader =new Loader();

this.addChild(loader);

loader.x=65;

loader.y=50;

//Note: listeners are added to the contentLoaderInfo property of 'loader'

Instead of adding our 'loader' to the Display List as we did above, you may want to extract its content;
that is, the downloaded Bitmap, and add the Bitmap as a child of, say, the MainTimeline. Extracting
downloded content is especially important if you want to process that content. For example, if
you want to access the pixel information of the downloaded Bitmap. If that is what you want,
the alternative code looks as follows. Delete the lines:

In the example presented here, we place the code on the Timeline of our fla file.
If you'd like to know how the code would look like placed in a Document Class,
and what AS3 classes would then need to be imported explicitly check out:
How To Find the AS3 Classes that Must be Imported in a Custom AS3 Class.
In the latter How-To, we use the example whose functionality is the same as here.