(Last Updated 11/18/98)




Sleepy

Java Script Image PreLoading



Doc

Dopey Grumpy

Happy

Sneezy

Bashful


Check out your favorite Dwarf.


Images are objects. They normally are created automatically each time an "IMG" tag is encountered. This allows the page to load quicker since it only loads Images when they are required. The problem is that the loading delay is then transferred to the time the image is called for. This can create annoying results when trying to change images with actions such as mouse overs, etc.

With Netscape 3, Java Script officially added the Image Object to Java Script. These Objects have two important properties: name and src (source). In Scripts, Image Objects are created and assigned to variables using the "new Image()" constructor. (A constructor is a method that instantiates {Thats defines an instance in OOPs'ese & I know it isn't a real word} an object; assigns it propertities, assigns memory to it, and initializes it.) This ability to instantiate the Object in Java Script means the images may be defined and loaded in the header section of the page prior to their tags being encountered.




The header code to preload the images is:
<SCRIPT LANGUAGE="Javascript">

preLoad = new Array ("sleepy.jpg","doc.jpg","dopey.jpg", "grumpy.jpg","happy.jpg","sneezy.jpg","bashful.jpg" )
ImageList = new Array ();

for (i in preLoad) { ImageList[i] = new Image(107,85);
ImageList[i].src = preLoad[i];
}
</SCRIPT>
In this snippit, the first line instantiates a 7 element string array and loads it with the image file names for the 7 dwarfs; The next line instantiates the image array; and The final 4 lines are a loop to fill the image array. In the loop, the first line sets the name property for each element of the array and declares it an image and the second line sets the src property.

The code to utilize these images is then of the form: onMouseOver="document.images[0].src=ImageList[0].src" This line accesses the first image in the list (arrays are numbered starting at 0).



Contact Carl Paulson with questions,
or Visit my pages.