I'm trying to preload about 200 images using the following:
var total_images = 0;
var loaded_cnt = 0;
var tempImg = new Object();
function precache_array(a,path){
for(var i = 0; i < a.length; i++){
tempImg[path + a[i]] = new Image();
tempImg[path + a[i]].src = path + a[i];
tempImg[path + a[i]].onLoad = image_loaded(a[i]);
}
}
function image_loaded(image){
console.log(image + " is loaded: " + loaded_cnt + " of " + total_images);
if(loaded_cnt == total_images){
for (var img in tempImg) {
document.write("<br><br>" img + "<br><br>");
document.write('<img src="'+img+'" />');
}
}
}
precache_array is called multiple times using various arrays I have grouped together, like:
images_arr = "image1.gif,image2.jpg,etc3.png".split(",");
total_images = images_arr.length;
precache_array(images_arr,"images/");
What happens is that all the new Image()'s are created and my console.log outputs that they have trigged the onLoad event. I decided to put in a document.write(<\img>) just to output the image also because my tests haven't been showing that the images are being cached.
While the images from the document.write are loading pretty fast, the browser (FF3) is stuck in perpetual "loading".
So my question is: is there a better way to do this precaching of images or is there something wrong with the way that I am doing it, but not really seeing?
Thanks so much.