views:

68

answers:

2

Hay, i'm using this script

function preloader(images){
         var i = 0;
         imageObj = new Image();


         // start preloading
         for(i=0; i<=images.length; i++){
            imageObj.src=images[i];
            imageObj.onLoad = check(i, images.length / 2);
         };

    }

and passing a bunch of images into it to preload.

the check() function is this

check = function(e,i){
        if( e == i ){
             run_fading_gallery(imgcode);
            $(".loading").hide();
        };
    }

But it doesnt seem to be working.

Any ideas? Or is there anything i can use online already?

A: 

images.length / 2 will not be a whole number if there are an odd number of images in the array, hence it will never be equal to i in the check function. Try Math.floor:

function preloader(images){
     var i = 0;
     imageObj = new Image();


     // start preloading
     for(i=0; i<=images.length; i++){

        imageObj.onLoad = check(i, Math.floor(images.length / 2));
        imageObj.src=images[i];
     };

}
Mark B
I think there is a problem with imageObj.onLoad(). The function doesn't seem to be called once the image has been loaded, but once the image has been requested. Any ideas?
dotty
Ah, perhaps add the event before you set the `src` - I've edited my code to show this now.
Mark B
I don't understand that comment. In your question you said you wanted to perform an action after 50 percent were loaded?
Mark B
+1  A: 

The thing is that you set only 1 imageObj and changing its source and event handler. Why don't you try creating an image object for each image? (in your loop).

To be more specific:

function preloader(images){
         var i = 0;

         // start preloading
         for(i=0; i<=images.length; i++){
            imageObj = new Image();
            imageObj.src=images[i];
            imageObj.onLoad = check(i, images.length / 2);
         };

    }
Daniel S
What's the difference, when you rewrite the imageObj anyway?
Petr Peller
If you modify the same object, the browser will stop loading the previously set src. Also, you'll only get a load event for the last image, which isn't what you want. Also, it should be .onload, not .onLoad.
foolip