In Example 16-1, our animation does not begin until the user clicks the Start button, which allows plenty of time for our images to be loaded into the cache. But what about the more common case in which we want to automatically begin an animation as soon as all the necessary images are loaded? It turns out that images, whether created on screen with an <IMG> tag or off screen with the Image() constructor, have an onLoad() event handler that is invoked when the image is fully loaded. Example 16-2 is an update to the previous example which shows how we could automatically start the animation as soon as the images are loaded.
<!-- The image that will be animated. Give it a name for convenience. --> <IMG SRC="images/0.gif" NAME=animation> <SCRIPT> // Count how many images have been loaded. When we reach 10, start animating. function count_images() { if (++num_loaded_images == 10) animate(); } var num_loaded_images = 0; // Create the off-screen images and assign the image URLs. // Also assign an event handler so we can count how many images have been // loaded. Note that we assign the handler before the URL, because otherwise // the image might finish loading (e.g., if it is already cached) before // we assign the handler, and then we'll lose count of how many have loaded! images = new Array(10); for(var i = 0; i < 10; i++) { images[i] = new Image(); // Create an Image object images[i].onload = count_images; // assign the event handler images[i].src = "images/" + i + ".gif"; // tell it what URL to load } function animate() // The function that does the animation. { document.animation.src = images[frame].src; frame = (frame + 1)%10; timeout_id = setTimeout("animate()", 250); // display next frame later } var frame = 0; // Keep track of what frame of the animation we're on. var timeout_id = null; // This allows us to stop the animation. </SCRIPT> <!-- Buttons to control the animation. Note that we don't let the user -- start the animation before all the images are loaded. --> <FORM> <INPUT TYPE=button VALUE="Start" onClick="if (timeout_id==null && num_loaded_images==10) animate()"> <INPUT TYPE=button VALUE="Stop" onClick="if (timeout_id) clearTimeout(timeout_id); timeout_id=null;"> </FORM>
In addition to the onLoad() event handler, the Image object also supports two others. The onError() event handler is invoked when an error occurs during image loading, such as when the specified URL refers to a corrupt image data. The onAbort() handler is invoked if the user aborts the image load (for example, by clicking the Stop button in the browser) before it has finished. For any image, one (and only one) of these handlers will be called. In addition to these handlers, each Image object also has a complete property. This property is false while the image is loading, and is true once the image has loaded or once the browser has stopped trying to load it. That is, the complete property becomes true once one of the three possible event handlers is invoked.