JavaScript Image Preloader | 2 | WebReference

JavaScript Image Preloader | 2

To page 1current page

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.




<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";




   // now create some elaborate tree structure using the preloaded images





<body onload="ip = new ImagePreloader(aImg, onPreload);">

   <div id="theDiv"></div>




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:

About the Author

Guyon Roche is a freelance web developer in London, Great Britain. He specializes in Windows platforms with an interest in bridging the gaps between different technologies, see for more details. He can be reached via e-mail at

To page 1current page

Created: June 5, 2003
Revised: January 14, 2004