如何知道何时加载特定"div"中的所有图像?

Mis*_*hko 17 html javascript jquery javascript-events

我的HTML页面的一部分如下div:

<div id="images_wrapper">
  <img ... />
  <img ... />
  <img ... />
  ...
</div>
Run Code Online (Sandbox Code Playgroud)

最初,这div是隐藏的,我只在加载所有图像时显示它:

$(window).load(show_images_wrapper);
Run Code Online (Sandbox Code Playgroud)

但是,如果我没有弄错,show_images_wrapper只有在加载所有页面时才会调用.我想show_images_wrapper在内部所有图像images_wrapper加载后立即调用,并且不要等到所有页面都加载完毕.

我试过了:

$("#images_wrapper").load(show_images_wrapper);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

我该怎么做?

use*_*716 24

使用length[docs]属性设置计数器的数量,在图像加载时递减.

var imgs = $("#images_wrapper > img").not(function() { return this.complete; });
var count = imgs.length;

if (count) {
    imgs.load(function() {
        count--;
        if (!count) {
            $("#images_wrapper").show();
            alert('all done');
        }
    });
} else {
    $("#images_wrapper").show();
}
Run Code Online (Sandbox Code Playgroud)

所述的not()[文档]方法是从其中它们的匹配的设定的图像去除.complete属性true.这意味着图像已经下载,可能是由浏览器缓存的.

当然,load()[docs]方法会在每个图像完成加载时触发.

示例: http ://jsfiddle.net/uhmAR/1/


编辑:更改它,以便容器将显示是否所有图像都被缓存.


编辑:

上面的另一个变体是绑定.load()到所有图像,并使用filter()[docs]方法获取那些.complete,并只是手动调用.load()它们.

这消除了对if/else语句的需要.

var imgs = $("#images_wrapper > img")
var count = imgs.length;

imgs.load(function() {
    count--;
    if (!count) {
        $("#images_wrapper").show();
        alert('all done');
    }
}).filter(function() { return this.complete; }).load();
Run Code Online (Sandbox Code Playgroud)

示例: http ://jsfiddle.net/uhmAR/3/


ale*_*lex 10

我写了一个jQuery插件,可以做到这一点.

$('#images_wrapper').waitForImages(function() {
   // Done.
});
Run Code Online (Sandbox Code Playgroud)

或者,

var images = $('#images_wrapper img'),
    imagesLength = images.length;

images.load(function() { 

    if ( ! --imagesLength) {
        // Done.
    }

});
Run Code Online (Sandbox Code Playgroud)