Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Preloading images - a nice "gotcha" 4

Status
Not open for further replies.
Dec 8, 2003
17,047
0
0
GB
Just when you think you know it all, along comes a nice "gotcha" that makes you realise that there's always new stuff to learn.

Take image preloading. Here's the code I was using this morning, which is similar to code I've used for many years:

Code:
var filenames = ['someImage.jpg', 'anotherImage.jpg', 'yetAnotherOne.gif'];
for (var loop=0, loop<filenames.length; loop++) {
	var img = new Image();
	img.src = filenames[loop];
}

Our QA guy came up to me this morning and asked me to prove the images were preloading. I tried to do so - but found that only 2 of the 5 images in my array were (certainly in IE 6).

I realised that because the "img" variable was being re-used before the image had completely finished loading, the image was being discarded - thus not being cached.

The fix was to store a reference to "img" so that the image wasn't discarded - even when "img" was re-used:

Code:
var preloadImages = [];
var filenames = ['someImage.jpg', 'anotherImage.jpg', 'yetAnotherOne.gif'];
for (var loop=0, loop<filenames.length; loop++) {
	var img = new Image();
	img.src = filenames[loop];
	preloadImages[preloadImages.length] = img;
}

Hopefully this will save somebody else the same grief I had when proving preloading works.

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
good stuff
 
I've always done it the way BRPS discovered DOES work because that's the way I learned, but never thought about it. Makes sense, though, so it looks like I got lucky. :)#

Thanks to the guy who taught me about preloading images at the ISP where I used to work!

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top