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:

<script>

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");
   elem.id = "preload_img"+i; // this is optional
   elem.style.position = 'absolute';
   elem.style.visibility = 'hidden';
   elem.style.left = '0px';
   elem.style.top = '0px';
   elem.style.width = '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
   elem.style.height = '10px';
   elem.style.background = "url('"+image_loc[i]+"') no-repeat left top";
   document.body.appendChild(elem);
}

</script>


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