dotty
dotty

Reputation: 41433

Preload a bunch of images from an array of file names, do function after 50% are done

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?

Upvotes: 2

Views: 1001

Answers (3)

Sam
Sam

Reputation: 6142

It will not work. Suppose you have a 100 images. Images load asynchronously. If the first image loaded is image number 50, then the function will say 50 images have been loaded, while only 1 image is loaded.

Upvotes: 0

Mark Bell
Mark Bell

Reputation: 29745

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];
     };

}

Upvotes: 0

Daniel Sorichetti
Daniel Sorichetti

Reputation: 1951

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);
         };

    }

Upvotes: 1

Related Questions