Run a function when all images are loaded

后端 未结 2 1253
温柔的废话
温柔的废话 2021-01-25 17:46

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.onl         


        
相关标签:
2条回答
  • 2021-01-25 18:27

    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 讨论(0)
  • 2021-01-25 18:52

    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);
        }
    };
    
    0 讨论(0)
提交回复
热议问题