Images often take several extra time to download from a Web server. If images change in response to user actions then you may want the same fast response that users are accustomed to. It may be an irritating situation while users are waiting for image(s) to be downloaded for a page and the page is loading slowly due to such images.
Objects created in memory are not seen on the page at all but their presence in the document code forces the browser to load images when the page gets loaded. The Image object constructor function is used to create the memory type of image object as follows:
var myImage = new Image(width, height)
Parameters to the constructor function are the pixel width and height of the image. These dimensions should match the
<img/> tag’s width and height attributes. Once the image object exists in memory, you can then assign a file name or URL to the
src property of that image object, where img1.jpg is your image in the current directory.
myImage.src = "img1.jpg"
When a browser encounters a statement assigning a URL to an image object’s
src property, the browser loads that image into the image cache. All users see is some extra loading information in the status bar, as if another image were in the page. By the time the entire page loads, all images generated in this way are tucked away in the image cache. You can then assign your cached image’s
src property or the actual image URL to the
src property of the document image created with the
document.images.src = myImage.src
The change to the image in the document is instantaneous.
At the time of the page loading several statements are executed immediately. These statements create four new image objects in memory and assign filenames to the objects’
src property. These images are loaded into the image cache when the page loads. In the body part of the document, an
<img/> tag loads one of the images as a starting image.
A select element lists user-friendly names for images while housing the names of image objects already precached in memory. When the user makes a selection from the dropdown, the
loadCached() function extracts the selected item’s value which is a string version of the image object name.
To convert a string name to a reference to the object of that same name, I have used the
src property of that object, so the
eval() function is applied to a string version of the reference to an image object’s
src property. The
src property of the chosen image object is assigned to the
src property of the visible image object on the page, and the precached image appears instantaneously.