Is it possible to detect when all images are loaded via a jQuery event?
Ideally, there should be a
$(document).idle(function()
{
}
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.
$.get('http://www.your_domain.com/image.jpg', imgLoaded);
function imgLoaded(){
console.log(this, 'loaded');
}
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();
}
});
});
}
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');
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
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.