JavaScript animation works by substituting one image with another. The new image should be ready to replace the original image as quickly as possible. For this to happen the image must already be loaded into the computer's memory (also known as cache). If the replacement image isn't already cached it will have to be loaded from the much slower network, resulting in delays in your animation.
The most common way to cache, or pre load images, is to write a script similar to the following:
<SCRIPT language="javascript">
if (bAnimate){
img1= new Image();
img2= new Image();
img3= new Image();
img4= new Image();
img5= new Image();
img6= new Image();
The script at the left caches six images into the computer's memory. None of these images are displayed yet, they're just loaded from the network for later use.

To cache an image you need to make a new Image() object. 

img1= new Image();
and then assign an image file to the newly created object. 
Notice that we only load the images if the bAnimate variable is TRUE. This way we avoid errors on older browsers.
The weird thing about caching images this way is that the new Image objects are not useable for other tasks--all they do is pre load (or cache) the images.

Another way to pre load the images is to literally put them some place on your document. If you don't want them to show you can always do this:

<IMG SRC="myimage.gif" WIDTH=0 HEIGHT=0>

This technique is not as good as the earlier method because it leaves a "nearly invisible" image on your web page and is subject to termination and errors, resulting in a very visible "image not found" error.

[Previous Lesson]    [Tutorial Home Page]    [Next Lesson]