确定何时jQuery load()完成了多个图像的加载

Identify when jQuery load() has finished loading multiple images

本文关键字:图像 加载 何时 jQuery load      更新时间:2023-09-26

我有一个脚本,使用jQuery的getScript()函数从tumblr帐户动态加载博客文章。

脚本响应是一个JSON结构tumblr_api_read,其中包含(除其他外)图像url。

function read(blogName) {
    var imageUrls = [];
    $.getScript("http://" + blogName + ".tumblr.com/api/read/js", function() {
        imageUrls = getImageUrls(tumblr_api_read.posts); // returns an array of URLs to use as img src attributes
    }).done(function(script, textStatus) {
        loadImages(imageUrls);
        processTumblrResponse(); // ### ONLY EXECUTE WHEN IMAGES ARE LOADED!!
    });
}

我在函数loadImages()中使用imageUrls数组,通过jquery构建的var $temporaryImageContainer<img/> s注入DOM,然后进行一些进一步的处理。

var imgAjaxComplete = false;
var imgCount = 0;
function loadImages(imageUrls, $temporaryImageContainer) {
    while (!imgAjaxComplete) {
        for (srcKey in imageUrls) {
            var $image = $("<img>", {"id" : "imageUrl" + srcKey, "src" : imageUrls[srcKey]})
                .load(function() {
                    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                        console.log("Error loading image: " + imageUrls[srcKey]);
                    } else {
                        $temporaryImageContainer.append($image);
                        console.log("Loaded image: " + imageUrls[srcKey]);
                    }
                });
            ++imgCount;
        }
        if (imgCount == imageUrls.length) {
            imgAjaxComplete = true;
            imgCount = 0;
        }
    }
    console.log("loadImages() complete");
}
function processTumblrResponse() {
    console.log("Images loaded. Running processTumblrResponse()");
    // further processing here...
}

这个问题是loadImages()中的for循环在其他任何事情之前执行(我认为这就是正在发生的事情),它只尝试加载imageUrls中的最后一个图像src n次(其中n是imageUrls.length)。

是否有可能在我执行额外处理之前识别注入DOM的所有图像何时完成加载?

JSON太大了,不能在这里发布,但如果需要上下文,请告诉我。

将函数loadImages替换为这里:

function loadImages(imageUrls, $temporaryImageContainer) {
        for (srcKey in imageUrls) {
            var $image = $("<img>", {"id" : "imageUrl" + srcKey, "src" : imageUrls[srcKey]})
                .load(function() {
                    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                        console.log("Error loading image: " + imageUrls[srcKey]);
                    } else {
                        $temporaryImageContainer.append($image);
                        console.log("Loaded image: " + imageUrls[srcKey]);
                    }
                    imgCount++;
                    checkIfImagesAreLoaded();
                });
        }
}
function checkIfImagesAreLoaded() {
    if (imgCount === imageUrls.length) {
        imgCount = 0;
        imgAjaxComplete = true;
        console.log("loadImages() complete");
    }
}

至于解释,for循环在其他任何事情之前完成,因为jQuery load函数只在加载图像时执行作为参数传入的方法,所以它不会立即被调用。

编辑:

您不应该在Javascript中使用for (x in array),因为该循环用于迭代对象的属性。不幸的是,最佳实践是使用for (var i = 0; i < length; i++) ...

查看W3Schools的循环文档。

你也可以使用:

yourArray.forEach(function(item) {
    //Do crazy stuff here
});

但是forEach()是ES5的一部分,在IE8及以下的旧浏览器中是不支持的。