JavaScript Image Preloader | 2
[previous] |
JavaScript Image Preloader
The three event handler functions act in pretty much the same way; after recording the type of completion (load, error or abort), the onComplete() method of the ImagePreloader object is called. This method counts the number of images that have been processed. When the count matches the total number of images, the call-back function is called with the array of Image objects and a count of the number of images that loaded correctly as arguments.
Note: While I've included the onload, onerror and onabort functions in the ImagePreloader prototype, they are not actually used as methods of the ImagePreloader class. However, this offers a convenient way to namespace the function names.
Making use of the ImagePreloader class is easy. During the body.onload event (or any time afterwards), an instance of the ImagePreloader class is created with an array of image URLs and a call-back function. Providing the images have all loaded, they may be referenced in the new HTML safely.
<html>
<head>
<script type="text/javascript" src="ImagePreloader.js"></script>
<script type="text/javascript">
var aImg = ["node.gif", "plus.gif", "minus.gif", "line.gif", "gap.gif"];
var ip = null;
function onPreload(aImages, nImages)
{
  var oDiv = document.getElementById("theDiv");
  if ( nImages = aImg.length )
  {
     oDiv.innerHTML = "Images did not load properly";
     return;
  }
 Â
  // now create some elaborate tree structure using the preloaded images
  ...
}
</script>
</head>
<body onload="ip = new ImagePreloader(aImg, onPreload);">
  <div id="theDiv"></div>
</body>
</html>
Conclusion
In this article I have introduced an ImagePreloader
class that manages the loading of multiple images and notifies the caller when
it is complete and the images are ready to be used. For a complete listing of
the ImagePreloader code with a demonstration of how different methods of DHTML
fare when adding images to the page, visit:
www.silver-daggers.co.uk/demo/ImagePreloader.html
About the Author
Guyon Roche is a freelance web developer in
[previous] |
Created: June 5, 2003
Revised: January 14, 2004
URL: https://webreference.com/programming/javascript/gr/column3/1