我有一个脚本,使用jQuery的getScript()
函数动态加载博客文章从tumblr帐户。确定何时jQuery加载()已完成加载多个图像
脚本响应是一个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!!
});
}
我使用imageUrls阵列中我的功能loadImages()通过jQuery构建变种$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...
}
与此麻烦的是,for
环路loadImages()
别的(我认为这是发生了什么反正),它只是不断尝试加载最后一个图像的src在imageUrls
n次(其中n是imageUrls.length
之前执行)。
是否有可能确定何时注入到DOM中的所有图像都已完成加载之前执行附加处理?
JSON太大而无法在此处发布,但请告知我是否需要上下文。
+1为循环信息,但我不清楚什么时候调用checkIfImagesAreLoaded()?用setTimeout试了一下,但我仍然看到相同的行为。 –
对不起,你应该在'load'函数传递的回调结束时使用'checkIfImagesAreLoaded()'。查看我刚刚编辑的内容。 – alexbchr