...

View Full Version : Best Way to Pre-Load Images?



KaliK
03-22-2011, 08:58 PM
I have done quite a bit of research on the web but I can't seem to find a general consensus on the best way to pre-load images. It seems some feel CSS is best and some feel JavaScript is best while others use a combination of the two.

Does anyone have an easy and trusty formula for pre-loading images that works across FF, Safari, IE and Opera?

adamchronister8
03-23-2011, 12:36 AM
I personally prefer to use CSS so that I can use Javascript for more difficult tasks. I think these methods should work fine across all browsers (not sure about IE6 though). http://devilsworkshop.org/css-trick-preload-image/

bullant
03-23-2011, 02:38 AM
Does anyone have an easy and trusty formula for pre-loading images that works across FF, Safari, IE and Opera?
I normally use javascript.

For a 1D array of images, something like this


var picData = ['num1.jpg','num2.jpg','num2.jpg','num2.jpg'];
picO = new Array();
for(i=0; i < picData.length; i++){
picO[i] = new Image();
picO[i].src = picData[i];
}
For a 2D array of images something like this


var loopPics = [
['num1.jpg','num2.jpg','num3.jpg','num0.jpg'],
['num4.jpg','num5.jpg'],
['num7.jpg','num8.jpg','num9.jpg']
];
//preload the images
var picsO = new Array();
for(i=0; i < loopPics.length; i++){
picsO[i] = new Array();
for(j=0; j < loopPics[i].length; j++){
picsO[i][j] = new Image();
picsO[i][j].src = loopPics[i][j];
}
}

bullant
04-14-2011, 04:38 AM
I always use Javascript!


I'm glad you resurrected this thread because the method I posted earlier still works fine as long as I don't want to use the Image Object's width property before the Image object's src is assigned to an <img> in IE9.

For example:

This code in the <head>



<script type="text/javascript">

var picData = ['num1.jpg','num2.jpg','num2.jpg','num2.jpg'];
picO = new Array();

for(i=0; i < picData.length; i++){
picO[i] = new Image();
picO[i].src = picData[i];
}

window.onload=function(){
alert(picO[0].width+' '+picO[0].height);
}
</script>outputs '0 0' in IE9 and '200 300' in FF4 and the latest versions of the major browsers. 200 and 300 are the actual width and height of num1.jpg

Earlier versions of IE seem to work as FF4 does.

It appears that the window.onload event in IE9 does not take into account if all the images have completed downloading via the above FOR loop :( whereas FF4 and the others do.

The workaround I am using is to preload the images in hidden <img>'s at the top of the <body> and then loading them into an Image object to get the jpg's actual width and height. This is working in IE9, FF4 and the other majors.

Have I missed or misunderstood something in the the way IE9 works?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum