已加载图像的 jQuery 事件

是否可以通过 jQuery 事件检测所有图像的加载时间?

理想情况下,应该有一个

$(document).idle(function()
{
}

或者

$(document).contentLoaded(function()
{
}

但我找不到这样的东西。

我想过附上这样一个活动:

$(document).ready(function()
{
var imageTotal = $('img').length;
var imageCount = 0;
$('img').load(function(){if(++imageCount == imageTotal) doStuff();});
}

但是,如果图像加载失败,这会中断吗?在正确的时间调用该方法至关重要。

137303 次浏览

If you want to check for not all images, but a specific one (eg. an image that you replaced dynamically after DOM is already complete) you can use this:

$('#myImage').attr('src', 'image.jpg').on("load", function() {
alert('Image Loaded');
});

Use of the jQuery $().load() as an IMG event handler isn't guaranteed. If the image loads from the cache, some browsers may not fire off the event. In the case of (older?) versions of Safari, if you changed the SRC property of an IMG element to the same value, the onload event will NOT fire.

It appears that this is recognized in the latest jQuery (1.4.x) - http://api.jquery.com/load-event - to quote:

It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.

There is a plug-in now to recognize this case and IE's "complete" property for IMG element load states: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js

There's a note on the ahpi.imgload.js plugin at the moment saying that it is currently broken, and to try this gist instead: https://gist.github.com/797120/7176db676f1e0e20d7c23933f9fc655c2f120c58

You can use my plugin waitForImages to handle this...

$(document).waitForImages(function() {
// Loaded.
});

The advantage of this is you can localise it to one ancestor element and it can optionally detect images referenced in the CSS.

This is just the tip of the iceberg though, check the documentation for more functionality.

Per jQuery's documentation, there are a number of caveats for using the load event with images. As noted in another answer, the ahpi.imgload.js plugin is broken, but the linked Paul Irish gist is no longer maintained.

Per Paul Irish, the canonical plugin for detecting image load complete events is now at:

https://github.com/desandro/imagesloaded

imagesLoaded Plugin is way to go ,if you need a crossbrowser solution

 $("<img>", {src: 'image.jpg'}).imagesLoaded( function( $images, $proper, $broken ){
if($broken.length > 0){
//Error CallBack
console.log('Error');
}
else{
// Load CallBack
console.log('Load');
}
});

If You Just Need a IE WorkAround,This Will Do

 var img = $("<img>", {
error: function() {console.log('error'); },
load: function() {console.log('load');}
});
img.attr('src','image.jpg');

As per this answer, you can use the jQuery load event on the window object instead of the document:

jQuery(window).load(function() {
console.log("page finished loading now.");
});

This will be triggered after all content on the page has been loaded. This differs from jQuery(document).load(...) which is triggered after the DOM has finished loading.

  function CheckImageLoadingState()
{
var counter = 0;
var length = 0;


jQuery('#siteContent img').each(function()
{
if(jQuery(this).attr('src').match(/(gif|png|jpg|jpeg)$/))
length++;
});


jQuery('#siteContent img').each(function()
{
if(jQuery(this).attr('src').match(/(gif|png|jpg|jpeg)$/))
{
jQuery(this).load(function()
{
}).each(function() {
if(this.complete) jQuery(this).load();
});
}
jQuery(this).load(function()
{
counter++;
if(counter === length)
{
//function to call when all the images have been loaded
DisplaySiteContent();
}
});
});
}

For same-origin images, you could use:

$.get('http://www.your_domain.com/image.jpg', imgLoaded);


function imgLoaded(){
console.log(this, 'loaded');
}
$( "img.photo" ).load(function() {


$(".parrentDiv").css('height',$("img.photo").height());
// very simple


});

I created my own script, because I found many plugins to be quite bloated, and I just wanted it to work the way I wanted. Mine checks to see if each image has a height (native image height). I've combined that with the $(window).load() function to get around the issues of caching.

I've code commented it quite heavily, so it should be interesting to look at, even if you don't use it. It works perfectly for me.

Without further ado, here it is:

imgLoad.js script

Waiting for all images to load...
I found the anwser to my problem with jfriend00 here jquery: how to listen to the image loaded event of one container div? .. and "if (this.complete)"
Waiting for the all thing to load and some possibly in cache !.. and i have added the "error" event... it's robust across all browsers

$(function() { // Wait dom ready
var $img = $('img'), // images collection
totalImg = $img.length,
waitImgDone = function() {
totalImg--;
if (!totalImg) {
console.log($img.length+" image(s) chargée(s) !");
}
};
$img.each(function() {
if (this.complete) waitImgDone(); // already here..
else $(this).load(waitImgDone).error(waitImgDone); // completed...
});
});

Demo : http://jsfiddle.net/molokoloco/NWjDb/

window.load = function(){}

Its fully supported by all browsers, and it will fire an event when all images are fully loaded.

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload