
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 imagestypically
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.