Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto check if images have loaded using Javascript?

In the OnLoad handler of my webpage I'm trying to check if all images have loaded correctly.

I'm iterating over all <img> tags and check them with my isImageLoaded() function. Unfortunately my function only works with Firefox and IE up to version 8.

Any suggestions how I can get it to work in IE 9 and 10?

function isImageLoaded(img) {
    // check for IE
    if (!img.complete) {
        return false;
    }
    // check for Firefox
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }
    // assume it's ok
    return true;
}

Update: It turns out the main culprit is that OnLoad can be fired before all image are loaded by IE9+. What would be a better trigger to check the images in the page ? I would prefer to check them all at once and not with individual OnLoad / OnError handlers.

like image 491
Gene Vincent Avatar asked Mar 20 '13 08:03

Gene Vincent


People also ask

How can I check image load?

You can use the . load() event handler, like this: $("#myImg"). load(function() { alert('I loaded!

How do I know if my img src is valid?

To check if an img src is valid: Add an error event listener on the img element. If the src is invalid, set it to a backup image. Alternatively, hide the image.


1 Answers

In the OnLoad handler of my webpage I'm trying to check if all images have loaded correctly.

I'm assuming you are using body.onload or <body onload="">? This should still mean that all images are all loaded — however, by using:

window.addEventListener('load', function(){
  /// everything in the page has loaded now
});

Or for older versions of IE:

window.attachEvent('onload', function(){
  /// everything in the page has loaded now
});

You'll get a more consistent behaviour across browsers, and I know for a fact that window.onload will only trigger once everthing has loaded (that includes all other resources like javascript and css however). This link could be interesting:

window.onload vs <body onload=""/>

So the above should make your function a little redundent, unless you are injecting images into the page after the onload event has fired. If however, you wanted to speed things up and not have to wait for everything to download you could use a dom ready listener and then implement the method mentioned by kennypu:

Cross Browser Dom Ready

Just as an added note, as far as I'm aware, image.complete should work for all modern browsers:

https://developer.mozilla.org/en-US/docs/DOM/HTMLImageElement

like image 197
Pebbl Avatar answered Oct 24 '22 13:10

Pebbl