20.3. Building a Preloader that Displays Load Percentage
Problem
You want to build a preloader that continually updates a display of the percent loaded.
Solution
Divide getBytesLoaded( ) by getBytesTotal( ), multiply the output by 100, and use a dynamic text field to display the output.
Discussion
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:
stop();
var nPreloaderInterval:Number = setInterval(this, 'checkPreloader', 100);
function checkPreloader():Void {
var nLoadedBytes:Number = this.getBytesLoaded();
var nTotalBytes:Number = this.getBytesTotal();
tProgress.text = Math.round(nLoadedBytes / nTotalBytes * 100) + '% downloaded';
if(nLoadedBytes >= nTotalBytes) {
clearInterval(nPreloaderInterval);
play();
}
}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 tProgress.
See Also
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access