Inside JavaScript
Precaching Images and the Image Object
JavaScript supports an Image object that enables you to hold images in memory and work with them using many of the same properties of the <IMG> element. One use for the Image object is to download images you'll use later to avoid download delays, precaching those images. You do that by creating an Image object, setting its height and width properties for the image you want to precache, and then setting the Image object's src property to load the image into the Image object. When you want to display the precached image in a web page, just set the src property of an image to the Image object's src property. Here's an example showing how this works. Note that the second image is precached as soon as the page loads, but only displayed when the user clicks a button (you'll need version 6+ if you're using Netscape Navigator): (Listing 15-08.html on the web site)
<HTML> <HEAD> <TITLE> Precaching Images </TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- var precache = new Image(216, 72) precache.src="image2.jpg" function display() { document.getElementById("img1").src = precache.src } // --> </SCRIPT> </HEAD> <BODY> <H1>Precaching Images</H1> <IMG ID="img1" WIDTH="216" HEIGHT="72" SRC="image1.jpg"> <FORM> <INPUT TYPE="BUTTON" ONCLICK="display()" VALUE="Click Me!"> </FORM> </BODY> </HTML> In this way, using the Image object, you can store images in memory and use them when you're ready for them. This is particularly useful for JavaScript-supported animation. |