Preloading Images with JavaScript
Preloading images is when images are loaded into the browser's cache so that when they are needed they are displayed immediately. This is often done in JavaScript rollover effects.
Using JavaScript, images can be loaded into the browser's cache with the Image object. Here is an example script that preloads three images:
<script type="text/javascript">
<!--
if (document.images)
{
image1 = new Image(100, 100);
image1.src = "myimage1.gif";
image2 = new Image(468, 60);
image2.src = "myimage2.gif";
image3 = new Image(50, 20);
image3.src = "myimage3.gif";
}
//-->
</script>
The above example preloads three images called "myimage1.gif", "myimage2.gif" and "myimage3.gif". This format is usually
used when installing any type of image rollovers. Note that only the "rollover" image needs to be preloaded, not the initial image that is loaded anyway.
To use the code above yourself, simply replace the image locations with your own and put in the appropriate widths and heights. The syntax is image = new
Image(width, height); to create a new Image object. Then the location of the image is set using image.src = "location";.
Usually this script would be place within the head section of your HTML document.
Old Browsers
Notice that we check first for the existence of document.images. This prevents older browsers that don't support the Image object from giving a JavaScript error.