Flash 8 Cookbook | Page 2
20.2 Building a Simple Preloader
You want to create a basic preloader, which will ensure smooth playback of a movie.
Attach a preloader script to the first frame of the movie.
To add a simple preloader to any movie, attach the following script to the first frame of the timeline:stop( ); var nPreloaderInterval:Number = setInterval(this, "checkPreloader", 100);
This script stops the playhead in the first frame, preventing further playback, until the preloader has verified that the entire SWF has loaded. It then uses an interval function to poll the SWF for the download progress every 100 milliseconds or so. When the number of downloaded bytes equals the total number of bytes, it knows that the file has downloaded entirely. At that point, it stops the interval and plays the timeline.
From a functional standpoint, this script accomplishes what it sets out to: it guarantees the smooth playback of the movie. However, it communicates none of this to the user. That is, while the script is busy determining whether the movie has fully loaded, the user sees only the content on frame 1. At a minimum, you should also put a message in frame 1 that indicates that the movie is loading and will begin playback when it has loaded. Users will have no way of knowing how long they will have to wait, but at least they won't initially assume the movie is broken. Place the contents of the main movie beginning on frame 2 or another frame, which you can specify by substituting a gotoAndPlay() action in place of the play() action.
To test the functionality of the preloader, add it to a Flash document with a large bitmap, sound, or other asset on frame 2 or later and test the movie (Control > Test Movie). Be sure to choose View > Show Streaming for the full effect.
See Also: Recipe 20.1, Recipe 20.3, Recipe 20.4
20.3 Building a Preloader that Displays Load Percentage
You want to build a preloader that continually updates a display of the percent loaded.
getBytesTotal(), multiply the output by 100, and use a dynamic text field to display the output.
The basic preloader script discussed in the previous recipe serves as the foundation for this preloader script. With the preceding script, nothing happens until the movie is fully downloaded, at which time the if statement checking load status evaluates to true, a
play() action is executed, and the preloader movie clip is removed.
In this variation of the script, I've added a line of code (shown in boldface) that outputs the percent that has loaded to a dynamic text field on the stage:
In addition to adding the script, you need to add the dynamic text field to the stage in frame 1. Create a dynamic text field, and give it an instance name of
See Also: Recipe 8.2, Recipe 20.2