Use the load()
(docs) method against the window
.
$(window).load(function() {
// this will fire after the entire page is loaded, including images
});
Note: On newer jQuery versions use $(window).on('load', function(){ ...});
Or just do it directly via window.onload
.
window.onload = function() {
// this will fire after the entire page is loaded, including images
};
If you want a separate event to fire for each image, place a .load()
on each image.
$(function() {
$('img').one('load',function() {
// fire when image loads
});
});
Or if there's a chance an image may be cached, do this:
$(function() {
function imageLoaded() {
// function to invoke for loaded image
}
$('img').each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
});
EDIT:
In order to perform some action after the last image loads, use a counter set at the total number of images, and decrement each time a load handler is called.
When it reaches 0
, run some other code.
$(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);
}
});
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…