Visualizing the Page Loading State with a Progress Bar


if (document.images[i].complete) {   loaded++; } 

Whether or not a page has been completely loaded cannot be determined by JavaScript alone, but at least it can be sufficiently estimated. The complete property of an image provides a Boolean value telling whether the image has been completely loaded. Also, an image supports the load event, so onload can be used to trigger code execution after the image has been loaded.

The following code iterates through all images on the page and counts how many of them have been completely loaded. This generates an estimated percentage of how much of the page has been fully loaded. (Of course, not included are applets and embedded media; also, the image file sizes are not taken into account.)

The Loading Progress Bar (loadprogress.html)

<script language="JavaScript"   type="text/javascript"> function showprogress() {   if (document.images.length == 0) {     return false;   }   var loaded = 0;   for (var i=0; i<document.images.length; i++) {     if (document.images[i].complete) {       loaded++;     }   }   var percentage = Math.round(     100 * loaded / document.images.length);   document.getElementById("progress").innerHTML =     percentage + "% loaded";   if (percentage == 100) {     window.clearInterval(ID);   } } var ID = window.setInterval("showprogress();", 500); </script> <p name="progress">0% loaded</p> 

In order to actually reproduce this effect, you have to embed images in your page that take quite long to load, either because they are really large or because the server is under a heavy load. The code downloads for this book include the PHP script gfx.php that relies on PHP's GD extension and creates a randomly colored image with a time delay of up to 15 seconds. Figure 3.3 shows the result when two out of three graphics have been loaded.

Figure 3.3. The third graphic is still loading.


Note

Other interesting events for images are abort (when the loading of the image is aborted by the user) and error (when there is an error loading the image, for instance, when the file does not exist). They can be used with the onabort and onerror event handlers.


Using Image Maps

JavaScript can also be used within client-side image maps, but only in relatively few scenarios:

  • Every link in the image map can be a javascript: link, thus enabling the browser to call JavaScript when the user clicks on a hotspot in the map.

  • Events like mouseover, mouseout, and load are also available within image maps for shapes defined in the <map> element.

  • The image map associated with an image can be set via JavaScript, using the useMap property. However, usually there is only one image map suitable for one image.





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