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.
You can use the . load() event handler, like this: $("#myImg"). load(function() { alert('I loaded!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With