Sergei Basharov
Sergei Basharov

Reputation: 53920

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?

Upvotes: 1

Views: 388

Answers (2)

R1234
R1234

Reputation: 484

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.

Upvotes: 0

Bj&#246;rn
Bj&#246;rn

Reputation: 29411

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

Upvotes: 1

Related Questions