20.2. Building a Simple Preloader

Problem

You want to create a basic preloader, which will ensure smooth playback of a movie.

Solution

Attach a preloader script to the first frame of the movie.

Discussion

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);

	function checkPreloader():Void {
	  var nLoadedBytes:Number = this.getBytesLoaded();
	  var nTotalBytes:Number = this.getBytesTotal();
	  if(nLoadedBytes >= nTotalBytes) {
	    clearInterval(nPreloaderInterval);
	  play();
	  }
	}

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 ...

Get Flash 8 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.