jquery callback after all images in dom are loaded?

前端 未结 3 622
野性不改
野性不改 2020-11-29 18:51

How can I fire an event when all images in the DOM are loaded? I\'ve googled a lot. I\'ve found this, but it doesn\'t seem to work:

jQuery event for images loaded

3条回答
  •  野性不改
    2020-11-29 19:24

    Below is what I came up with, using deferred objects and $.when instead of using a counter.

    var deferreds = [];
    $('img').each(function() {
        if (!this.complete) {
            var deferred = $.Deferred();
            $(this).one('load', deferred.resolve);
            deferreds.push(deferred);
        }
    });
    $.when.apply($, deferreds).done(function() {
        /* things to do when all images loaded */
    });
    

    Let me know if there is any caveats.

提交回复
热议问题