在dom中的所有图像加载后jquery回调?

时间:2011-02-01 01:06:12

标签: jquery image load

如果在加载DOM中的所有图像时如何触发事件? 我google了很多。我发现了这个,但它似乎不起作用:

jQuery event for images loaded

3 个答案:

答案 0 :(得分:112)

window使用load()(docs)方法。

$(window).load(function() {
    // this will fire after the entire page is loaded, including images
});

或者直接通过window.onload完成。

window.onload = function() {
    // this will fire after the entire page is loaded, including images
};

如果您想为每张图片触发单独的事件,请在每张图片上放置.load()

$(function() {
    $('img').one('load',function() {
        // fire when image loads
    });
});

或者,如果有可能缓存图像,请执行以下操作:

$(function() {
    function imageLoaded() {
       // function to invoke for loaded image
    }
    $('img').each(function() {
        if( this.complete ) {
            imageLoaded.call( this );
        } else {
            $(this).one('load', imageLoaded);
        }
    });
});

修改

为了在最后一次图像加载后执行某些操作,请使用在图像总数中设置的计数器,并在每次调用加载处理程序时递减。

当它达到0时,运行其他一些代码。

$(function() {
    function imageLoaded() {
       // function to invoke for loaded image
       // decrement the counter
       counter--; 
       if( counter === 0 ) {
           // counter is 0 which means the last
           //    one loaded, so do something else
       }
    }
    var images = $('img');
    var counter = images.length;  // initialize the counter

    images.each(function() {
        if( this.complete ) {
            imageLoaded.call( this );
        } else {
            $(this).one('load', imageLoaded);
        }
    });
});

答案 1 :(得分:6)

以下是我提出的内容,使用延迟对象和$.when而不是使用计数器。

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 */
});

如果有任何警告,请告诉我。

答案 2 :(得分:5)

我遇到用户113716编辑的解决方案遇到的一个问题是,破碎的图像会使计数器永远不会达到0.这对我来说是固定的。

.error(function(){
  imageLoaded();
  $(this).hide();
});