31 July, 2010

Pre load images with Javascript

In all UI Rich web applications, it is very common to pre-load images. General method to do this is to use Javascript. We can load images by creating client side images before page gets loaded. It is a simple technique and can be done with 2 lines of code.

var testImage = new Image();
testImage.src = "test.jpg";

With the above lines of code test.jpg will loaded in the DOM. As the images are cached by browsers, whenever we send a new request for test.jpg, the image will be loaded immediately from cache. With this pre-loading technique there wont be any time lag in getting the image also no display lag for the user. This can be used in the scenarios like displaying image gallery with all the thumbnails loaded on first load of the page, image change on hovering/click of some links.

We can do this preloading in html page using an image tag with height and width set to zero or wrapping the dynamic image in a hidden div. But, advantage with this approach is the imag wont be loaded to the page.

No comments:

Post a Comment