views:

42

answers:

1

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.

A: 

JavaScript is case-sensitive: you want to set the "onload" property of your Image objects, not "onLoad".

EDIT 1: You seem to be missing a "+" in one of the document.write() calls, where you prepend some line breaks to the image HTML.

EDIT 2: Instead of inserting the image into the document as HTML, better to insert the Image object directly into the DOM. In Prototype-speak, it would be:

var container = $('myDomContainersID');
tempImg.each(function(img) { container.insert(img); });

You might have to make your generic Object an Array instead to make the above code work. I haven't tested it.

jQuery can do a similar thing, if you prefer, with minor syntax differences.

Warren Young
Thanks for that, though this doesn't fix my problem. "onLoad" was triggering the event in FF3, though I am not going to presume that it will in everything else. But I changed this to "onload" and continue to have difficulty.
liamgriffiths
Added more possible answers above
Warren Young