advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   TIP BANK
Browse DevX
Download the code for this article
Have you ever needed to load images sequentially in JavaScript? What workarounds did you find? Let us know on the Web technologies discussion forum.
Partners & Affiliates
advertisement
advertisement
advertisement
advertisement
 

Develop a Reusable Image Cache in JavaScript

The asynchronous download ability built into today's browser DOMs is a great way of getting image-heavy pages to build faster, but it doesn't mesh well with JavaScript's single-threading execution model. Use our image cache API to build scripts that work hand-in-hand with asynchronous objects and their events.  


advertisement
cripting a browser's Document Object Model may be easy these days, but while the DOM is highly functional in some areas, it remains distinctly inflexible in others. Asynchronous operations like image loading have always been a gray area, with plenty of useful events exposed by the DOM, but little advice on how to utilize them to full effect. Knowing when a block of images has loaded is often critical to achieving the page layout, functionality, and interactivity you require. In this article I'll explain how I developed a few simple classes to do just that, thereby making image-loading headaches a thing of the past.

Open up any Web site authored with Macromedia's Dreamweaver, and chances are you'll see a bit of code at the top of the page that looks like this:


function MM_preloadImages()
{
//v3.0
var d=document;
if(d.images)
{
if(!d.MM_p)
d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
for(i=0; I<a.length; i++)
{
if (a[i].indexOf("#")!=0)
{
d.MM_p[j]=new Image;
d.MM_p[j++].src=a[i];
}
}
}
}
Actually, it probably won't look quite as structured, since the whole lot's compacted into five lines, but you get the general idea. A little later you may well see an onload handler that looks something like this:

<body onLoad="MM_preloadImages('icon1.gif', 'icon2.gif',
'icon3.gif')">
The purpose of this code is to "preload" a set of images—typically onmouseover and onmouseout rollovers. If the images weren't preloaded, you would notice a perceptible delay the first time you moved the mouse over a rollover image before the rollover image would display, as the browser would have to go off and fetch it from the server then and there. In fact, "preloading" is a bit of a misnomer, as code like this makes no guarantees that it will have finished loading all the rollovers before you need to access them; it simply kicks off loading them when the document itself is ready.

It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com.
Already a member?



advertisement