22 August 2011
Basic knowledge of working with ActionScript 3 and familiarity with ActionScript 3 concepts.
Intermediate
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.
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 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:
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 (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:
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.
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.
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:
// 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);
Loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, functionName);
functionName (e:ProgressEvent):void{
// determine the percentage loaded
}
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.
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:
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:
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.
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.
holder.load(new URLRequest(fescue.swf));
// the URLRequest instance specifies the name of the file to load
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:
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.e.target = LoaderInfo).bytesLoaded and bytesTotal properties of the LoaderInfo object are used to dynamically generate the numbers displayed in the text field.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).
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.
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"));
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:
loadingClip appears briefly and then the external SWF content loads.
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.
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.
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:
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.
| 04/23/2012 | Auto-Save and Auto-Recovery |
|---|---|
| 04/23/2012 | Open hyperlinks in new window/tab/pop-up ? |
| 04/21/2012 | PNG transparencies glitched |
| 04/01/2010 | Workaround for JSFL shape selection bug? |
| 02/13/2012 | Randomize an array |
|---|---|
| 02/11/2012 | How to create a Facebook fan page with Flash |
| 02/08/2012 | Digital Clock |
| 01/18/2012 | Recording webcam video & audio in a flv file on local drive |