在jQuery中,当你这样做:

$(function() {
   alert("DOM is loaded, but images not necessarily all loaded");
});

它等待DOM加载并执行您的代码。如果没有加载所有的图像,那么它仍然执行代码。这显然是我们在初始化任何DOM内容(如显示或隐藏元素或附加事件)时所需要的。

假设我想要一些动画我不想让它运行直到所有图像都加载完毕。jQuery中有官方的方法来做到这一点吗?

最好的方法是使用<body onload="finished()“>,但除非迫不得已,我真的不想这么做。

注意:在ie浏览器的jQuery 1.3.1中有一个bug,它实际上是在执行$function(){}内的代码之前等待所有图像加载。所以如果你正在使用这个平台,你会得到我正在寻找的行为,而不是上面描述的正确行为。


当前回答

使用imagesLoaded PACKAGED v3.1.8(最小化时6.8 Kb)。这是一个相对较老的项目(自2010年以来),但仍然是活跃的项目。

你可以在github上找到: https://github.com/desandro/imagesloaded

他们的官方网站: http://imagesloaded.desandro.com/

为什么它比使用更好:

$(window).load() 

因为您可能希望动态加载图像,就像这样:jsfiddle

$('#button').click(function(){
    $('#image').attr('src', '...');
});

其他回答

用jQuery我来这个…

$(function() {
    var $img = $('img'),
        totalImg = $img.length;

    var waitImgDone = function() {
        totalImg--;
        if (!totalImg) alert("Images loaded!");
    };

    $('img').each(function() {
        $(this)
            .load(waitImgDone)
            .error(waitImgDone);
    });
});

演示:http://jsfiddle.net/molokoloco/NWjDb/

这样,当body或任何其他容器(取决于您的选择)内的所有图像都加载时,您可以执行一个操作。纯JQUERY,不需要插件。

var counter = 0;
var size = $('img').length;

$("img").load(function() { // many or just one image(w) inside body or any other container
    counter += 1;
    counter === size && $('body').css('background-color', '#fffaaa'); // any action
}).each(function() {
  this.complete && $(this).load();        
});

到目前为止,没有一个答案给出了似乎是最简单的解决方案。

$('#image_id').load(
  function () {
    //code here
});

对于那些想要在$(window)之后收到请求的单个图像下载完成通知的人。Load触发,你可以使用image元素的Load事件。

例如:

// create a dialog box with an embedded image
var $dialog = $("<div><img src='" + img_url + "' /></div>");

// get the image element (as a jQuery object)
var $imgElement = $dialog.find("img");

// wait for the image to load 
$imgElement.load(function() {
    alert("The image has loaded; width: " + $imgElement.width() + "px");
});

我的解决方案类似于莫洛洛可。jQuery函数:

$.fn.waitForImages = function (callback) {
    var $img = $('img', this),
        totalImg = $img.length;

    var waitImgLoad = function () {
        totalImg--;
        if (!totalImg) {
            callback();
        }
    };

    $img.each(function () {
        if (this.complete) { 
            waitImgLoad();
        }
    })

    $img.load(waitImgLoad)
        .error(waitImgLoad);
};

例子:

<div>
    <img src="img1.png"/>
    <img src="img2.png"/>
</div>
<script>
    $('div').waitForImages(function () {
        console.log('img loaded');
    });
</script>