jQuery:一旦加载了图像的子集,就执行函数

jQuery: Execute function as soon as a subset of images have loaded

本文关键字:子集 执行 函数 图像 加载 jQuery      更新时间:2023-09-26

我有一个幻灯片,需要用jQuery初始化。初始化需要所有的幻灯片图像都被完全加载,这样我就可以得到它们的实际宽度和高度。我不能改变这部分。

考虑以下布局:

<div class="slideshow">
  <img />
  <img />
  <img />
</div>
<img />
<img />
<img />

我需要在幻灯片容器中的三个图像加载完毕后立即初始化幻灯片。我等不及页面上的其他图像都加载好了,因为可能有成千上万的图像。

你知道我该怎么解决这个问题吗?

根据我的评论,您可以将检查/加载行为封装在jQuery插件中,并返回一个类似的承诺:

$.fn.imagesLoaded = function () {
    var def = $.Deferred();
    var count = this.length;
    this.each(function () {
        if (this.complete) {
            if (!--count) {
                def.resolve();
            }
        } else {
            $(this).load(function () {
                if (!--count) {
                    def.resolve();
                }
            });
        }
    });
    return def.promise();
}

然后简单地使用如下:

$('.slideshow img').imagesLoaded().done(function () {
    alert("loaded");
});

以下是我最终使用的内容,比我希望的要复杂得多:

// Prepare the slideshow as soon as all of its images have been loaded
var slideshowImages = $('.slideshow img');
var slideshowImagesLoadedCount = 0;
// Check how many images have already been loaded
slideshowImages.each(function() {
    if(this.complete) {
        slideshowImagesLoadedCount++;
    }
});
// If all the images have loaded already, prepare the slideshow
if(slideshowImagesLoadedCount === slideshowImages.length) {
    prepareSlideshow();
} else {
    // Otherwise wait until all images have been loaded
    slideshowImages.load(function() {
        slideshowImagesLoadedCount++;
        if(slideshowImagesLoadedCount === slideshowImages.length) {
            prepareSlideshow();
        }
    });
}