Preloading Images Using JavaScript
There can be many instances where you would like to preload images in a HTML primarily for caching in order to serve the page better. This can be achieved by the use of Image objects in JavaScript. Image Object allow dynamic creation and manipulation of images in JavaScript, it is support by IE 4+ and Firefox.
Preloading Image
Preloading an image can be done by invoking a small JavaScript, that creates an image object and loads an image from the URL specified in the src parameter. See below
<head> <script type="text/javascript"> <!-- image01= new Image(); image01.src="http://www.google.co.in/intl/en_com/images/logo_plain.png"; image02= new Image(); image02.src="http://labs.google.com/images/labs_logo2.gif"; //--> </script> </head>
The most optimal place to trigger the preloaded is on the body onLoad(), so that the images will start loading once the page has completed loading.
Changing images in JavaScript
The most immediate function after loading/caching and image is to use it somewhere in the html page, this can be achieved easing using JavaScript
See Full Example below
<html>
<head>
<title>Page title</title>
<script language="JavaScript">
objImage1 = new Image();
objImage2 = new Image();
objImage3 = new Image();
cnt = 0;
function preLoadImages(){
// preload the image file
objImage1.src='http://www.google.com/logos/mlk09.gif';
objImage2.src='http://www.google.com/logos/newyear09.gif';
objImage3.src='http://www.google.com/logos/olympics08_opening.gif';
}
function changeImage() {
cnt++;
if (cnt==1) {
document.images['im'].src = objImage1.src;
}
else if (cnt==2) {
document.images['im'].src = objImage2.src;
}
else if (cnt==3) {
document.images['im'].src = objImage3.src;
cnt=0;
}
}
</script>
</head>
<body onLoad="preLoadImages()">
<form name="myWebForm">
<img name="im" src="http://www.google.com/logos/olympics06_opening.gif"><br>
<input type="button" name="Prev" value="Switch Image " onClick="changeImage()">
</form>
</body>
</html>


March 17th, 2010 at 9:23 am
Your website is awesome. I m gonna read more, gracias. Keep doing on blog.