Monday, September 29, 2008

Preload images in HTML using JavaScript

Preloading means loading an object (graphics, text, movie) before showing it to output.

A good example is of preloading in flash files, when you see a loader before displaying the content, and after loading site shows a smooth experience of flow of data.

This is mostly used when there is an mouser over images to be loaded. If user mouse overs an image and then you loads the new mouse-over image it may take a few seconds to load, which leads to a small blank image over the image area. By pre-loading the image you can show mouseover image instantly without any delay.

In this post I am explaining how to do preaload imags in HTML using JavaScript, without using flash.

We have to use the Head tag of html as this is the one which loads on first page executiution.

<head>

<script type=”text/JavaScript”>

if (document.images)
{
pic1= new Image(190,53);
pic1.src=”images/productSmall.gif”;

pic2= new Image(190,53);
pic2.src=”images/storeSmall.gif”;
}

</script>

</head>

The above code lods two images naming productSmall.gif and storeSmall.gif respictively from images directory. It creates a new object of image and assigns it a dimention and a file to load.

The document.imags condition has been used to determine that the browser supports the images or not.

No comments: