在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(){}内的代码之前等待所有图像加载。所以如果你正在使用这个平台,你会得到我正在寻找的行为,而不是上面描述的正确行为。


当前回答

$(window).load()只在页面第一次加载时起作用。如果你正在做动态的事情(例如:点击按钮,等待一些新的图像加载),这是行不通的。要实现这一点,你可以使用我的插件:

下载

/**
 *  Plugin which is applied on a list of img objects and calls
 *  the specified callback function, only when all of them are loaded (or errored).
 *  @version: 1.0.0 (Feb/22/2010)
 */

(function($) {
$.fn.batchImageLoad = function(options) {
    var images = $(this);
    var originalTotalImagesCount = images.size();
    var totalImagesCount = originalTotalImagesCount;
    var elementsLoaded = 0;

    // Init
    $.fn.batchImageLoad.defaults = {
        loadingCompleteCallback: null, 
        imageLoadedCallback: null
    }
    var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
        
    // Start
    images.each(function() {
        // The image has already been loaded (cached)
        if ($(this)[0].complete) {
            totalImagesCount--;
            if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
        // The image is loading, so attach the listener
        } else {
            $(this).load(function() {
                elementsLoaded++;
                
                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);

                // An image has been loaded
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
            $(this).error(function() {
                elementsLoaded++;
                
                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
                    
                // The image has errored
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
        }
    });

    // There are no unloaded images
    if (totalImagesCount <= 0)
        if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);

其他回答

对于那些想要在$(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");
});

我建议使用imagesLoaded.js javascript库。

为什么不使用jQuery的$(window).load()?

正如在https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load/26929951上的回答

这是一个范围问题。imagesLoaded允许你瞄准一组图像,而$(window).load()瞄准所有资产——包括所有图像、对象、.js和.css文件,甚至iframe。imagesLoaded很可能比$(window).load()更早触发,因为它的目标是较小的资产集。

其他使用图像加载的好理由

IE8+正式支持 许可证:MIT许可证 依赖性:没有 重量(缩小&压缩):7kb缩小(轻!) 下载构建器(有助于减肥):不需要,已经很小了 在Github上:是的 社区和贡献者:相当大,4000多名成员,尽管只有13名贡献者 历史和贡献:稳定,相对较老(自2010年以来),但仍然活跃的项目

资源

项目在github: https://github.com/desandro/imagesloaded 官方网站:http://imagesloaded.desandro.com/ 检查图像是否在JavaScript中加载(无错误) https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load Imagesloaded javascript库:浏览器和设备支持什么?

我写了一个插件,可以在图像加载到元素时触发回调,或者每加载一个图像就触发一次。

它类似于$(window).load(function() {..}),除了它允许您定义任何选择器进行检查。如果你只想知道什么时候所有的图片在#content(例如)已经加载,这是为你的插件。

它还支持加载CSS中引用的图像,如background-image, list-style-image等。

jQuery插件

GitHub库。 自述文件。 生产来源。 开发源码。

示例使用

$('selector').waitForImages(function() {
    alert('All images are loaded.');
});

jsFiddle的例子。

更多的文档可以在GitHub页面上找到。

$(window).load()只在页面第一次加载时起作用。如果你正在做动态的事情(例如:点击按钮,等待一些新的图像加载),这是行不通的。要实现这一点,你可以使用我的插件:

下载

/**
 *  Plugin which is applied on a list of img objects and calls
 *  the specified callback function, only when all of them are loaded (or errored).
 *  @version: 1.0.0 (Feb/22/2010)
 */

(function($) {
$.fn.batchImageLoad = function(options) {
    var images = $(this);
    var originalTotalImagesCount = images.size();
    var totalImagesCount = originalTotalImagesCount;
    var elementsLoaded = 0;

    // Init
    $.fn.batchImageLoad.defaults = {
        loadingCompleteCallback: null, 
        imageLoadedCallback: null
    }
    var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
        
    // Start
    images.each(function() {
        // The image has already been loaded (cached)
        if ($(this)[0].complete) {
            totalImagesCount--;
            if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
        // The image is loading, so attach the listener
        } else {
            $(this).load(function() {
                elementsLoaded++;
                
                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);

                // An image has been loaded
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
            $(this).error(function() {
                elementsLoaded++;
                
                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
                    
                // The image has errored
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
        }
    });

    // There are no unloaded images
    if (totalImagesCount <= 0)
        if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);

用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/