Posts Tagged ‘preload image’

Preloading multiple images in javascript

I needed to preload a set of images for a nav. menu using javascript. I googled “javascript preload” and found a few sites with examples. I followed the examples and adapted the code to my problem… it didn’t work.

You’ll find many sites that have examples for how to preload a set of images in javascript, such as this one, this one, this one, etc… They all basically have the same code, which as far as I can tell doesn’t work because they all have the same simple mistake.

Here’s my code after following the examples from these sites:

function preloadMenuImages()
{
pl =
new Image();
imgurl =
new Array();
imgurl[0] =
"images/nav_products_highlight.jpg";
imgurl[1] =
"images/nav_services_highlight.jpg";
imgurl[2] =
"images/nav_location_highlight.jpg";
imgurl[3] =
"images/nav_about_highlight.jpg";
imgurl[4] =
"images/nav_contact_highlight.jpg";

var i=0;
for(i=0; i<5; i++)
{
pl.src = imgurl[i];
}
}

I tested with IE7 and after the browser executes this code, the only image preloaded is the one referred to by imgurl[4], the last element in the array. I loaded the page with IE6 and Firefox 2, and it was obvious that the preload function didn’t work in these browsers either.

It seems that simply assigning to the src member doesn’t load the image. You actually have to create an Image object then assign to the src member. So the correct code is:

function preloadMenuImages()
{
imgurl =
new Array();
imgurl[0] =
"images/nav_products_highlight.jpg";
imgurl[1] =
"images/nav_services_highlight.jpg";
imgurl[2] =
"images/nav_location_highlight.jpg";
imgurl[3] =
"images/nav_about_highlight.jpg";
imgurl[4] =
"images/nav_contact_highlight.jpg";

var i=0;
for(i=0; i<5; i++)
{
pl =
new Image();
pl.src = imgurl[i];
}
}

Simple enough.

Of course it’s simple after you find the bug. I spent about an hour trying to figure out why my original code wasn’t working; never thinking that there could be a mistake in the code I found online.