How to know when all images inside a specific “div” are loaded?

前端 未结 2 835
难免孤独
难免孤独 2020-12-14 02:33

Part of my HTML page is the following div:

... &
相关标签:
2条回答
  • 2020-12-14 03:09

    I wrote a jQuery plugin that can do this.

    $('#images_wrapper').waitForImages(function() {
       // Done.
    });
    

    Alternatively,

    var images = $('#images_wrapper img'),
        imagesLength = images.length;
    
    images.load(function() { 
    
        if ( ! --imagesLength) {
            // Done.
        }
    
    });
    
    0 讨论(0)
  • 2020-12-14 03:12

    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/

    0 讨论(0)
提交回复
热议问题