开发者

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

开发者 https://www.devze.com 2022-12-22 04:35 出处:网络
Hay, i\'m using this script function preloader(images){ var i = 0; imageObj = new 开发者_开发百科Image();

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?


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

    }


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

}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消