Preloading Images Using Javascript

Image Preloading is quite often used when there is roll over images, image gallery for faster display of the images required.

What is image preloading?
It is the process of loading image to the browser’s cache before the image is required.We call all the image in advance so that it can be displayed wholly whenever it is required.

Script:

Here we use javascript image object(Image()) to preload images.

function preloadImages()
{
       // array of images that is required
       var imageArray = new Array('image1.jpg', 'image2.jpg'); 
       var img =  new Image(); // instance of Imag object;
       for(var i=0;i<imageArray.length;i++)
       {
             //puts the source for the image object
             img.src=imageArray[i];     
       }
 
}

Now use the function preloadImages on onload event inside the body tag..
Eg:

<body onload='preloadImages()'>

This will load all the images that has been provided on the image array as soon as the window loads.

410 views
Javascript

Comments

2 Responses to “Preloading Images Using Javascript”

Leave Comment

(required)

(required)