By Lou Barber
 
Created
22 August 2011
 

Requirements

 
Prerequisite knowledge

Basic knowledge of working with ActionScript 3 and familiarity with ActionScript 3 concepts.
 

 
User level

Intermediate
 

 
Required products

 
Sample files

Preloading is a term that describes the ability to track the loading of external content into Adobe Flash Player. A preloader typically displays a numeric or visual indicator of the percentage of content currently loaded. Preloading serves two purposes by delivering a better user experience (providing feedback) and ensuring that the functionality works as expected (content needed for user interactions is available to the application). See Pretty Loaded for some creative examples of different styles of preloaders.
 
Preloaders facilitate the loading process for SWF files, images, audio, text, and video content. It is essential to preload files with larger file sizes to prevent the project from appearing broken as it attempts to load the requested content.
 
The ability to preload content in Flash Player has existed for many years. Developers have devised many ingenious ways to facilitate the loading of external content (including other SWF files) to achieve optimal performance on a wide variety of devices.
 
ActionScript 3 includes designated classes (objects) to handle the preloading of content. In this article, you'll explore classes used to develop preloader functionality and improve playback of your Flash projects.
 

 
Understanding the Loader and LoaderInfo objects

Preloaders developed in Adobe Flash Professional use two primary display classes: the Loader class and the LoaderInfo class. To get a better understanding of how these classes work together, consider an analogy of the king and the messenger in medieval times.
 
The king's responsibilities are to preside over his land. The messenger's responsibility is to deliver information to the king. Imagine that the king is very popular. As a result, there is a great quantity of gifts to deliver. As the messenger brings the gifts into the castle, he continually alerts the king to let him know the percentage of gifts that has been loaded into the king's chamber. In this example, the messenger plays the role of the LoaderInfo class (see Figure 1).
 
The messager
Figure 1. The messager knows the information (LoaderInfo) about the progress of the delivery.
The messager is rapidly conveying the gift packets to the king. It is his primary task to deliver any new gifts, at a moment's notice. He is in charge of all aspects of the delivery and is careful to track both statistics and characteristics of the gifts he delivers.
 
The LoaderInfo object contains the following information pertaining to the loaded content:
 
  • File size
  • File location
  • Flash Player version
  • Bytes currently loaded
  • Total number of bytes
The LoaderInfo object does all the heavy lifting to deliver the gifts as quickly as conditions allow. He is always busy processing the items and accounting for them.
 
Conversely, the king stands stoically. He is the ruler and has neither the time nor the patience to keep track of little things. The king only wants his "gifts" delivered promptly. The king plays the role of the Loader class (see Figure 2).
 
The king would like his gifts (content) delivered immediately.
Figure 2. The king would like his gifts (content) delivered immediately.
The king (Loader object) does not have any information about the loaded content. However, he loves the gifts and holds on to them.
 
The Loader object holds the external content that is loaded, including the following file types:
 
  • SWF
  • JPEG
  • PNG
  • GIF
In order to pass the LoaderInfo object information to the Loader object, you'll use the contentLoaderInfo property, like this:
 
Loader.contentLoaderInfo = LoaderInfo
This may seem like a strange way to pass information to the Loader object but it works great. Because the contentLoaderInfo property is data typed as LoaderInfo, you can only pass a LoaderInfo object to the contentLoaderInfo property. If you look back at the "medieval times" analogy, this means that only the messenger is allowed to send information to the king—no one else.
 

 
Reviewing the ActionScript code used to create preloaders

In this section, you'll examine the list of classes used when developing preloaders. Take a moment to view the documentation in the ActionScript 3 Reference for the Adobe Flash Platform by clicking the links below. You'll use the following classes, methods, and properties in the next section when you build the preloader script:
 
Here's a brief summary of each class:
 
URLRequest: Specifies the content file to be loaded.
 
Loader: Loads and displays the loaded content. Create new instances of the Loader object using the following code:
 
var loader:Loader = new Loader();
LoaderInfo: Holds the information about the loaded content. This information is passed to the Loader with the contentLoaderInfo property.
 
Note: You cannot create a new instance of the LoaderInfo object, like this:
 
var loader_info:LoaderInfo = new LoaderInfo();
 
The LoaderInfo object is automatically created when you execute the Loader.load() method.
 
ProgressEvent: Tracks the progress of the content loading in Flash Player.
 
Event: Determines when the content has loaded into Flash Player.
 

 
Working with events

Almost all ActionScript objects broadcast events automatically. As you write the code, you choose to add code to access and respond to the events of interest as they occur. As certain events are broadcast, other events are triggered by functions.
 
Here is an overview of the events commonly used when creating a preloader:
 
  1. The preloader script begins with an event (loading a file). The code below creates an instance of the URLRequest object and specifies the file to load:
// create a new instance or URLRequest and load a file var myRequest:URLRequest = new URLRequest("your file to load"); var myLoader:Loader = new Loader(); myLoader.load(myRequest);
  1. The preloader tracks the progress of the event. In the code snippet below, the "functionName" monitors the progress of the loading content. To achieve this, the properties of the ProgressEvent class are used to obtain the percentage of data loaded:
Loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, functionName); functionName (e:ProgressEvent):void{ // determine the percentage loaded }
  1. The following code determines when the content has loaded successfully:
Loader.contentLoaderInfo.addEventListener(EVENT.COMPLETE, functionName); functionName (e:EVENT):void{ // the file loaded successfully }
The three event-driven sections shown above comprise the primary functionality of all preloaders. In a real-world preloader, you would add a bit more ActionScript to check for errors and display the progress status to the user.
 
Now that you've reviewed the basics, it's time to build the preloader using the provided sample files.
 

 
Creating a sample preloader

Begin by downloading the sample files folder provided at the beginning of this article. After downloading the sample files, uncompress the folder and save it on your desktop.
 
The sample files contain the following two files:
 
  • index.fla contains the preloader code that will load the external file
  • fescue.swf is a large file (3.2 MB) that is loaded into index.swf at runtime
Note: Files that are around 3 MB or larger are a good size to test preloaders locally. If you attempt to load smaller files, the file may load so quickly that you cannot actually see the preloader at work.
 
Follow these steps to build the preloader:
 
  1. Launch Flash Professional CS5 or later. Open the file named index.fla. This file contains a movie clip instance on the Stage with the instance name loadingClip.
  2. Take a moment to examine the movie clip by double-clicking it. The movie clip contains a dynamic text field. You'll add the code that displays a numeric percentage in the field to indicate to the user the progress of the content as it is loading (see Figure 3).
Movie clip containing a dynamic text field
Figure 3. The movie clip contains a dynamic text field that will be populated at runtime to display the percentage of content currently loaded.
  1. In the Timeline, select the actions layer. Open the Actions panel (Window > Actions). Click in the Script window on line 1 to begin entering code.
  2. Copy and paste the following code to create a new instance of the Loader class named holder. Use the addChild method to place the Loader class on the Stage:
var holder:Loader = new Loader(); // create a new instance of the loader class named holder addChild(holder); // put the instance on the Stage // by default, the holder is placed at X=0 and Y=0.
  1. Copy and paste the code below to set up the event listeners and event handlers:
holder.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoading); holder.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete); // event handlers function onLoading(e:ProgressEvent):void{ // check loading progress } function onComplete(e:Event):void{ // loading complete }
Note: The letter e is used to hold the data that will be received from the ProgressEvent. The letter e is a variable. This means that, from time to time, instead of seeing the letter e, you may see event, evt, or even myEvent. The naming convention is totally up to the developer. That data enables you to communicate with the LoaderInfo object by using the ProgressEvent's target property. This operation allows you to access the LoaderInfo properties bytesLoaded and bytesTotal. These properties are needed to display the numbers in the dynamic text field.
 
  1. Copy and paste the code below to load the external content file:
holder.load(new URLRequest(fescue.swf)); // the URLRequest instance specifies the name of the file to load
  1. Add the code below to track the progress of the content as it loads:
holder.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoading); // event handlers function onLoading(e:ProgressEvent):void{ // check loading progress var pcent:Number = e.target.bytesLoaded / e.target.bytesTotal * 100; loadingClip.loadingText.text = int(pcent) + "%"; } function onComplete(e:Event):void { // loading complete }
Review the previous code segment:
 
  • The e is data typed as a ProgressEvent object (e = ProgressEvent). This means that the data received from the ProgressEvent are stored in the variable e.
  • The target property of ProgressEvent is a reference to the object that triggered the event, the LoaderInfo object (e.target = LoaderInfo).
  • The bytesLoaded and bytesTotal properties of the LoaderInfo object are used to dynamically generate the numbers displayed in the text field.
  • The calculated percentage is stored in a variable called pcent, which is then displayed in the text field in the movie clip called loadingClip.
The result is a numeric indicator displayed in the dynamic text field that displays a number from 0% to 100% as the content is loaded (see Figure 4).
 
Percentage of the content currently loaded
Figure 4. The dynamic text field displays the percentage of the content currently loaded.
  1. Copy the last bit of code to add event handlers to hide the preloader element when the content file has finished loading:
holder.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoading); // event handlers function onLoading(e:ProgressEvent):void{ //check loading progress var pcent:Number = e.target.bytesLoaded / e.target.bytesTotal * 100; loadingClip.loadingText.text = int(pcent) + "%"; } function onComplete(e:Event):void { // load operation complete this.loadingClip.visible = false; }
Note: After the content of the SWF file has been loaded successfully, the visible property of loadingClip is set to false. If needed, you can add code to track the loading progress of other content files by setting the visible property to true.
 
  1. Test the movie (Control > Test Movie). The SWF with the preloader loads in Flash Player. The preloader appears quickly as the content of the external SWF file is loaded. Once the file finishes loading, the preloader text field disappears and the loaded content is displayed (see Figure 5).
Figure 5. The external SWF content is loaded into the preloader SWF file.
Figure 5. The external SWF content is loaded into the preloader SWF file.
When you are finished, close the Flash Player window and return to Flash Professional.
 
Note: To see a working example of the preloader, open index-complete.fla located in the sample files folder. Explore the working version in the Flash workspace.
 
Below if the entire code used in this example:
 
var holder:Loader = new Loader(); addChild(holder); holder.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoading); holder.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete); function onLoading(e:ProgressEvent):void { var pcent:Number = e.target.bytesLoaded / e.target.bytesTotal * 100; loadingClip.loadingText.text = int(pcent) + "%"; } function onComplete(e:Event):void { this.loadingClip.visible = false; } holder.load(new URLRequest("fescue.swf"));

 
Testing the preloader

In the last step of the previous section, you tested the movie and the content successfully loaded into the holder container. However, when you test the files locally, you cannot really test the performance of the preloader itself. By testing the movie, you generated the SWF file for the preloader project but the preloader graphic did not display the total progress of the loaded content.
 
In this section, you'll use the Simulate Download feature. You can use this method to test preloader files without uploading the assets to the web server. When you test the movie this time, you'll configure the connection speeds in Flash Player to simulate how the file downloads.
 
Note: When you build projects, it is a best practice to test the final version of the files on the web by uploading them to your host server. However, for the purposes of this tutorial (and when testing incremental changes to your project) this is a helpful strategy to save time.
 
Follow these steps to test the preloader using the Simulate Download settings:
 
  1. Test the movie by choosing Control > Test Movie.
  2. Flash Player loads the SWF file. The loadingClip appears briefly and then the external SWF content loads.
  3. While the movie is running, set the Simulate Download settings. Choose View > Download Settings > DSL (see Figure 6).
Figure 6. Choose DSL in the Download Settings.
Figure 6. Choose DSL in the Download Settings.
This selection configures the Simulate Download feature to load the external SWF file as though it is loading on a machine with a DSL connection.
 
  1. To run the Simulate Download feature, choose View > Simulate Download (see Figure 7).
Figure 7. Invoke the Simulate Download feature to test the preloader locally.
Figure 7. Invoke the Simulate Download feature to test the preloader locally.
Now when the movie plays using the Simulate Download feature, the percentage is displayed in the loaderClip as the SWF file loads. Once the percentage reaches 100%, the preloader text field disappears and the loaded content is displayed.
 

 
Where to go from here

The best way to research further is to create your own preloader file from scratch or use this sample project as the basis of creating a new project.
 
One concept you can explore is to create an animation, rather than displaying a numeric percentage indicator. Create a movie clip containing an animation that is exactly 100 frames long in the Timeline. Name the movie clip instance myPreloader. In Frame 1 of the actions layer, add the following code:
 
function onLoading(e:ProgressEvent):void { // check loading progress var pcent:Number = e.target.bytesLoaded / e.target.bytesTotal * 100; loadingClip.loadingText.text = int(pcent) + "%"; myPreloader.gotoAndStop(pcent);
In this example, every frame is equal to a percentage of the completed loading operation. Once the percentage equals 100%, it means that the myPreloader current frame number is also equal to 100 (the end of the animation).
 
You can create theme-specific animations to match your Flash projects. For example, a project that promotes a vineyard could display a wine bottle that pours wine into a glass until the glass is full. A car could rev up and drive off screen just as the content loads. The possibilities are only limited by your imagination.
 
Check out the following resources to learn more about creating preloaders:
 
Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights
 
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.