Monday, January 20, 2014

Preload Images using Javascript

There are times that you need to preload images on your web page to avoid the long load time required for a dynamic HTML site.

I've tried many examples found on the web but none of them are really working on today's browsers.

Here's my way of making this happen:


var image_loc = new Array('/image/pic1.jpg','/image/pic5.jpg','/image/pic13.jpg','/image/pic9.jpg');
var elem;

for (i = 0; i < image_loc.length; i++) {
   elem = document.createElement("span"); = "preload_img"+i; // this is optional = 'absolute'; = 'hidden'; = '0px'; = '0px'; = '10px'; // this can be bigger as long as it is not wider than the screen to avoid extra scroll bar appears at the bottom of the window = '10px'; = "url('"+image_loc[i]+"') no-repeat left top";


The trick is to create hidden elements and load the images to be preloaded into background. Those images will be hidden and located at the upper left corner of the screen. The location and size of the SPAN element can be of other values. Hope you like my first new trick in 2014!

No comments:

Post a Comment