JavaScript: Preload Images


Introduction

Author: Martin Warning
Year: 2007
License: Free

This example will preload images for a webpage. This is particularly useful if you use JavaScript or CSS hover to show a different image. By using preloaded images the user will directly see the mouse over image.

Code

Languages: The following code goes in the <head> part of the document:
<script language="JavaScript" type="text/javascript">
//<![CDATA[
	// in case the browser supports the images object
	if (document.images)
	{
	  image01=new Image(50,100);
	  image01.src="image01.gif";
	}
// End -->
//]]>
</script>

We use the if (document.images) part to limit the code execution to browsers that support the image object. new Image(50,100); creates a new image object with a width of 50 and a height of 100. You can omit the height and width and just declare new Image(); instead. image01.src="image01.gif"; is the url for the image to be preloaded. In case you want to load more than 1 image you would just use a different variable name (image02, image03, etc.) for each new image to be preloaded.


Example with various images and no width or height declared
<script language="JavaScript" type="text/javascript">
//<![CDATA[
	// in case the browser supports the images object
	if (document.images)
	{
	  image01=new Image();
	  image01.src="image01.gif";
	  image02=new Image();
	  image02.src="image02.gif";
	  image03=new Image();
	  image03.src="image03.gif";
	}
// End -->
//]]>
</script>


Pinternet.net: The world of beer on the Internet
Printed from: http://flyinglowlander.com/ (5/20/2012)
© FlyingLowander.com 2006 - 2012

Visit http://flyinglowlander.com for more XHTML, CSS, ASP and JavaScript examples, templates and tutorials.