spacer

Using the Loader Class in AS3

By Blue_Chi | Flash CS3 | ActionScript 3.0 | Beginner

The Loader Class is an ActionScript class that lets us load external assets (such as images and Flash files) at run time onto a Flash movie. Using such technique makes our Flash movie more efficient as you load specific files only when needed instead of embedding them regardless of whether the user ends up watching them or not. Separating our movie into distinct sections loaded at run time makes the website easier to update as you can update the external assets without going back to the main FLA. Our tutorial will teach you the basics on how to use the Loader Class to load an external asset. Check the example below to see the Loader Class in action:


The ActionScript 3.0 Loader Class replaces all the previous ActionScript 1/2 methods such as .loadMovie(), loadMovieNum() and the MovieClipLoader Class. It is the only native class for loading external graphical assets. Refer to our MovieClipLoader Class tutorial to learn how to load external assets in ActionScript 2.0.

Our tutorial is divided into the following sections:

  1. Basic Usage of the Loader Class
  2. Using the LoaderInfo Events with the Loader Class
  3. Creating a simple preloader for the Loader Class using the ProgressBar Component

Basic Usage of the Loader Class

The Loader Class can be used to load a JPEG, a GIF, a PNG, or an SWF file into another Flash movie during runtime. Using the Loader Class to do this simple task is quite easy as all it requires is merely creating an instance of the class and then using its .load() method to load the external asset. Showing the asset on the screen would obviously also require using the addChild() method to it to display the list.

For a quick practical example, create a new Flash movie in ActionScript 3.0 format, save the movie somewhere on your computer, then make sure that your external asset (for example, an image named myPhoto.jpg) is located in the same folder as your FLA file. Now go back to the FLA, right-click the only frame on the timeline, select Actions and then paste the code below to do the trick, we will explain the code in detail in a bit.

var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("myPhoto.jpg"));
addChild(my_loader);

You can now test your movie (Ctrl+Enter) to see that your image is loaded on the screen.

The first line of our code simply created an instance of the Loader Class, the instance name is my_loader.

var my_loader:Loader = new Loader();

The second line loaded the external image using the .load() method. This method requires the URL to be provided to it through the URLRequest Class. The URLRequest can be instantiated through different methods, the one shown in our code below is the shortest and easiest one to use.

var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("myPhoto.jpg"));
You can check the entry of the URLRequest Class in the ActionScript reference to learn more about it.

The final line of our code simply adds our instance of the Loader Class to the Display List so that we can see the image on the screen.

var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("myPhoto.jpg"));
addChild(my_loader);
The addChild() method adds the target object to the display list. If used on the main timeline without any qualification it will display the object on the screen, if used through an object, that target object will be displayed when the parent object is displayed.

The common usage of the Loader Class will require greater functionality involving tracking the downloading progress and performing specific actions when the loading progress completes. The next section will show you how to track the downloading progress of the Loader Class by using the various events available through its contentLoaderInfo.

Using the LoaderInfo Events with the Loader Class

It is possible to track the downloading progress of an instance of the Loader Class by reacting to the various events available through a property called contentLoaderInfo. This property is basically an instance of another class called LoaderInfo which can provide information for tracking the downloading progress of any asset. The contentLoaderInfo providers several events such as Event.COMPLETE, Event.INIT, and ProgressEvent.PROGRESS. To take a specific action at any of the stages identified by these events we simply attach a listener function to take care of the job.

The first event to discuss here is the Event.COMPLETE. This event is triggered when the external asset completes downloading and can be used to take a specific action when the file finishes loading, for example, take user to a specific scene to be shown along with the external asset. This event can be used using a code similar to the one below:

my_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, startListener);
function startListener (e:Event):void{
trace("Loading Completed");
}
Event Handling is the process by which all interactivity is programmed in ActionScript 3.0. An Event is a trigger event at which an action will be taken. This action is specified in a Listener Function. The event is linked to the listener function using the .addEventListener method. Events differ from one class to another, review the ActionScript to learn about the various events available to a specific class.

A very similar event to the Event.COMPLETE is the Event.INIT which is triggered when the external asset is ready to be used, whether fully downloaded or not. For example, the very few frames of an external SWF might be ready for display before the entire file is downloaded, so you might want to do something with these frames while you want for the rest of the movie to download. On the other hand, some files might be fully downloaded but not yet initialized as the initialization might take a second or two after the completion of the download process of a file, so you might want to wait for this file to be ready for usage before attempting to use that asset. To trigger an action when the external file has initialized you will need to use a code similar to the one below:

my_loader.contentLoaderInfo.addEventListener(Event.INIT, initListener);
function initListener (e:Event):void{
trace("Object Initialized");
}
Event.INIT is commonly used when attempting to retrieve the width and height of an image when it finishes loaded. Such property is not available instantly when the file finishes loading, so attempting to retrieve these properties using Event.COMPLETE fails, Event.INIT must be used instead.

The two events mentioned above cover the completion and readiness of the downloaded object, the next event is ProgressEvent.PROGRESS, which, as the name suggests, is responsible for tracking the downloading progress of the external file. The previous two events occur only once for each downloading process, but the progress event is executed repeatedly while the downloading process is still in progress. The most basic usage of it is as follows:

my_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
function progressListener (e:ProgressEvent):void{
trace("Loading In Progress");
}
Notice that the events for competition and initialization are a property of the Event Class, while the event for the progress is a property of the ProgressEvent Class.

The event can also be used to retrieve specific information about how much data has loaded by accessing the properties .bytesLoaded and .bytesTotal. The code below shows an example:

my_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
function progressListener (e:ProgressEvent):void{
trace("Downloaded " + e.bytesLoaded + " out of " + e.bytesTotal + " bytes");
}
You can simulate the downloading process by pressing Ctrl+Enter twice.

There is a forth event which we have not discussed called Event.OPEN which signifies the starting of the downloading process, we are not going to discuss this event because it's usage is similar to the other events and it is not widely used. Instead, we will talk about another property that is not really related to events but worth talking about. It is the .content property which refers directly to the externally loaded asset. This asset is to be used when you need to pass a command to an SWF file that you have loaded as you cannot pass that code to the instance of the Loader class instead:

my_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, startListener);
function startListener (e:Event):void{
addChild(my_loader.content)
}

This completes our coverage of the events and properties available to the Loader Class, it is possible to use the ProgressEvent properties to manually create a preloader, but our next section will show you a much easier trick for creating a preloader using the ProgressBar Component.

Creating a simple preloader for the Loader Class using the ProgressBar Component

We can use the events and properties of the LoaderInfo to create a graphical preloader, but why should we do that when we can use the readymade Flash components? Components are readymade movie clips with built-in functionality. You can access Components in Flash by going through Window>Components. We are going to use ProgressBar component to show the downloading progress, and will also make use of the Button component just to make our experiment a little bit fancier. Our end result is going to look something like the movie below:

In our little project the downloading process will be started when the button is clicked, the progress bar will be shown when the loading starts, and then the image will appear when it is fully downloaded. There are two main events in our movie:

  1. Event 1: Clicking of the button - when this event happens the loading process must start, the button must disappear, and the progress bar must appear.
  2. Event 2: Completion of the loading progress - when this event happens the image must appear and the progress bar must disappear.

We are going to do this in a step by step procedure.

Start off with a new Flash movie in ActionScript 3.0 format, save it in the same folder as your image (name the image "myPhoto.jpg"). We must have graphical instances of the components we need in our library to be able to use them in ActionScript. Go back to the Flash movie and drag and drop and instance of the Button Component and the ProgressBar Component onto the stage.

spacer

We said that we need these in our library and not really on stage, dragging an instance to the stage once at least puts them automatically in our library (Ctrl+L), we do not need them anymore on the stage, so just delete both of them now from the stage. We are ready to script our movie now, right-click the only frame on stage and select Actions to open the Action Panel.

We have the graphical assets of our components in the library, but to be able to use them in ActionScript we must also import the ActionScript classes to our movie, we can simply do that by using the import directive by pasting the following at the start of our code:

import fl.controls.ProgressBar;
import fl.controls.Button;

The first task for our movie is to create an instance of the Loader Class, though the .load() method will not called until later, but we still need to make our instance ready at the start:

import fl.controls.ProgressBar;
import fl.controls.Button;

var my_loader:Loader = new Loader();

We now need to create an instance of the Button component, that is a relatively easy job, we will also instantly set its label to "Load Image", position it on stage, and will show it on the screen all at the same time using the addChild() method.

import fl.controls.ProgressBar;
import fl.controls.Button;

var my_loader:Loader = new Loader();

var my_btn:Button = new Button();
my_btn.label = "Load Image";
my_btn.x = 100;
my_btn.y = 200;
addChild (my_btn);

We will now create our ProgressBar Component and will set it to work with our Loader Class by configuring its .source property, but will not show it on screen until later. We are also going to specify where on stage it should be positioned:

import fl.controls.ProgressBar;
import fl.controls.Button;

var my_loader:Loader = new Loader();

var my_btn:Button = new Button();
my_btn.label = "Load Image";
my_btn.x = 100;
my_btn.y = 200;
addChild (my_btn);

var my_pb:ProgressBar = new ProgressBar();
my_pb.source = my_loader.contentLoaderInfo;
my_pb.x = 100;
my_pb.y = 200;
The .source property of the ProgressBar Component sets the source of the loading progress. It is usually set the .contentLoaderInfo property of a Loader Class instance.

Our assets are now ready, we need to configure their actions now. We will first deal with the Button, we are going to attach an event to react to a click to the Button. We will attach a listener function to that event to do the following: (1) start the loading progress, (2) display the progress bar, (3) hide and delete the Button.

import fl.controls.ProgressBar;
import fl.controls.Button;

var my_loader:Loader = new Loader();

var my_btn:Button = new Button();
my_btn.label = "Load Image";
my_btn.x = 100;
my_btn.y = 200;
addChild (my_btn);

var my_pb:ProgressBar = new ProgressBar();
my_pb.source = my_loader.contentLoaderInfo;
my_pb.x = 100;
my_pb.y = 200;

my_btn.addEventListener(MouseEvent.CLICK, startLoading);
function startLoading(e:MouseEvent):void{
my_loader.load(new URLRequest("myPhoto.jpg"));
addChild(my_pb);
removeChild(my_btn);
my_btn=null;
}
Setting the value of a variable to null deletes the object if that object is not displayed on the screen and if that object cannot be referred to through another variable.

We now need to set up our next event to react the completion of the loading progress. To do that we need to attach an event listener to the .contentLoaderInfo property of our Loader Class, the task of the listener function here would be to (1) show the loaded asset and (2) hide and delete the progress bar.

import fl.controls.ProgressBar;
import fl.controls.Button;

var my_loader:Loader = new Loader();

var my_btn:Button = new Button();
my_btn.label = "Load Image";
my_btn.x = 100;
my_btn.y = 200;
addChild (my_btn);

var my_pb:ProgressBar = new ProgressBar();
my_pb.source = my_loader.contentLoaderInfo;
my_pb.x = 100;
my_pb.y = 200;

my_btn.addEventListener(MouseEvent.CLICK, startLoading);
function startLoading(e:MouseEvent):void{
my_loader.load(new URLRequest("myPhoto.jpg"));
addChild(my_pb);
removeChild(my_btn);
my_btn=null;
}

my_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, finishLoading);
function finishLoading(e:Event):void{
addChild(my_loader);
removeChild(my_pb);
my_pb = null;
}

That should do it. Test your movie and simulate download to see your progress bar working and your image showing up when the progress finishes.

This concludes our tutorial. The code below illustrates the simple usage of the Loader Class, the ProgressBar component and the Event.COMPLETE event. You may download the end source file from this link. Feel free to post at the Oman3D Forum if you have any questions.

- End of Tutorial.

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.