开发者

Run a function when all images are loaded

I use a function like this to load images from an array:

for (var i = 0; i < images_list.length; i++) {
            var img = new Image();
            img.onload = function() {
                images_objects.push(this);
                showImages(images_objects);
            };
            img.onerror = function() {

            };
            img.src = images_links[i].image_url;
        }

What I need to make work properly is showImages function.开发者_高级运维 Its purpose is to show all loaded images with jQuery when the images_object is filled with images from the array. Now it's placed incorrectly, just to give you an idea how I try to do it. I suppose there is something like a callback should be run after the images are loaded. How to do this better?


Just use a helper function to store the newly loaded image and to check to see if all images have been loaded, might work.

...
img.onload = function() {
    storeLoadedImage(this);
};
...

var storeLoadedImage = function(image) {
    images_objects.push(image);

    if (images_objects.length === images_list.length) {
        showImages(images_objects);
    }
};


You should not use it inside the loop. It will show all images loaded till ith iteration and not all loaded images if that's what you're trying to say. Just add this as the first line of the loop

if (i==images_list.length) {showImages(images_objects);}

What I understand is you want to display them once all of them have been loaded.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜