Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Preloading images

What is it? It is basically loading an image into cache before being used, so whenever we want to use it, bam, it appears instantaneously! Usually, when we load a page, all image are not preloaded-that's why we see these image becoming visible bit by bit. Why would we want to preload an image? Because it is the solution to avoiding having delays in between a change of image in effects like rollover images and image slideshows. So how do we preload images  in JavaScript? Simply by reating an instance of the image object in the HEAD section of the page, and assigning the image we wish to preload to its src property. Here's an example:

<head>
<script type="text/javascript">
<!--
image01= new Image()
image01.src="1.gif"
image02= new Image()
image02.src="3.gif"
//-->
</script>
</head>
  • Notice that the preloading of the image takes place within in <head></head> section of your webpage.
  • Recall what you've learned-we are creating an instance of the image object (we did something similar for the date object). By using the keyword "new", we have done that. Next we need to tell it what exactly to contain in it, by using the src property and pointing that to the actual path to the image. Repeat this for every image you wish to preload.

Now that we know how to preload images using Javascript, that facilitates the creation of JavaScript applications that demand a smooth transition between image changes. As promised, it's time now to look at how to create the classic rollover image effect!

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.