Preloading Images


var i = new Image(); i.src = ""; 

Although the mouseover effect from the previous phrase is easy to implement and nice to look at, it still has a structural flaw: After the mouse pointer moves over an image, the replacement graphic is loaded from the server. This leads to a certain latency and a possible negative user experience.

Therefore, it is desirable to preload these images after the page itself has been loaded. With JavaScript, you can instruct the browser to load the images. Then they are in the browser's cache (unless caching is disabled in the browser or the web server sends HTTP headers forbidding local caching) and load instantly when the hover effect is triggered.

To achieve this effect, you have to instantiate the JavaScript Image object and set its src property. This loads the image in the background, without even displaying it. You just have to make sure that the preloading is executed when the HTML page has been fully loaded, as the following listing shows:

Preloading Images (preload.html)

<script language="JavaScript"   type="text/javascript"> function preloadImage(url) {   var i = new Image();   i.src = url; } </script> <body onload="preloadImage('active.gif');"> </body> 

If several images have to be preloaded at once (for instance, if the whole navigation uses a hover effect), a more generic function accepting an array with images can be used:

Preloading Multiple Images (preload-array.html)

<script language="JavaScript"   type="text/javascript"> function preloadImages(urls) {   var img = new Array();   for (var i=0; i<urls.length; i++) {     img[img.length] = new Image();     img[img.length - 1].src = urls[i];   } } window.onload = function() {   var img = new Array(     "active.gif", "inactive.gif", "other.gif");   preloadImages(img); } </script> 

Tip

With standard HTML, you can preload images, as well, without having to display them:

<div style="display:none;">   <img src="/books/3/490/1/html/2/active.gif" height="1" width="1" />   <img src="/books/3/490/1/html/2/inactive.gif" height="1" width="1" />   <img src="/books/3/490/1/html/2/other.gif" height="1" width="1" /> </div> 


However, when you need these images only for JavaScript effects, you should only preload them using JavaScript. Otherwise, users without JavaScript would preload the files, as wellwithout seeing the visual (JavaScript) effects.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net