Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

javascript - How to know when all images inside a specific "div" are loaded?

Part of my HTML page is the following div:

<div id="images_wrapper">
  <img ... />
  <img ... />
  <img ... />
  ...
</div>

Initially, this div is hidden, and I show it only when all images are loaded:

$(window).load(show_images_wrapper);

However, if I'm not mistaken, show_images_wrapper will be called only when all the page is loaded. I would like show_images_wrapper to be called as soon as all images inside images_wrapper has been loaded, and don't wait until all the page is loaded.

I tried:

$("#images_wrapper").load(show_images_wrapper);

but it didn't work.

How should I do this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set up a counter to the quantity of the images using the length[docs] property, that is decremented as the images load.

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();
}

The the not()[docs] method is removing from the matched set the images where their .complete property is true. This means the image has already downloaded, and was perhaps cached by bhe browser.

Of course the load()[docs] method fires as each image finishes loading.

Example: http://jsfiddle.net/uhmAR/1/


EDIT: Changed it so that the container will show if all the images happened to be cached.


EDIT:

Another variation on the above is to bind the .load() to all the images, and use the filter()[docs] method to get the ones that are .complete, and just manually invoke the .load() on them.

This removes the need for the if/else statement.

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();

Example: http://jsfiddle.net/uhmAR/3/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...