Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching where an Image fails to load from a src url

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.

like image 913
Petruza Avatar asked Dec 08 '11 05:12

Petruza


People also ask

How do you show image errors in HTML?

In HTML, this can be done with the onerror attribute of the <img> tag.

Which tag is used for displaying information if an image fails to load?

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.

How do you know if an image has a broken link?

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.


1 Answers

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";
like image 110
jfriend00 Avatar answered Sep 16 '22 20:09

jfriend00