简体   繁体   English

加载所有图像后运行功能

[英]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. 我需要正确执行的工作是showImages函数。 Its purpose is to show all loaded images with jQuery when the images_object is filled with images from the array. 它的目的是当images_object被数组中的图像填充时,使用jQuery显示所有加载的图像。 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. 如果您要说的话,它将显示直到第i次迭代加载的所有图像,而不显示所有加载的图像。 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. 我了解的是,您希望它们全部加载后显示它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM