I need to load images in a webpage dynamically in Javascript, but need to catch if any image fails to load, how can I do this?
For instance:
try{
var img = new Image();
img.src = "404_not_found.png";
} catch( err ) {
// tried this but didn't work
}
Yes, I know I'm not even waiting for the image to onload
but when a 404 occurs, the onload method doesn't get called anyway.
In HTML, this can be done with the onerror attribute of the <img> tag.
The <img> tag has two required attributes: src - Specifies the path to the image. alt - Specifies an alternate text for the image, if the image for some reason cannot be displayed.
Find the URLs of pages with broken images You will see a "not found" or "404 error" note next to non-functioning links. For WordPress sites, there is a special plugin for identifying null links and images - Broken Link Checker. Add it to the administration panel and detect all nonexistent links found on the website.
Before you assign the .src
property, you need to set onload
, onerror
, and onabort
handler functions. And, you may want to also set a timer so you can assume it isn't going to load if none of the handlers have been called when the timer fires.
Here's a working example: http://jsfiddle.net/jfriend00/48JmQ/
var img = new Image();
img.onerror = function() {alert("error")};
img.onabort = function() {alert("abort")};
img.onload = function() {alert("success")};
img.src = "404_not_found.png";
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