Determine if file is corrupted in Javascript

I am adding images to HTML5 canvas using Javascript:

img = new Image(); 
img.addEventListener('load', loadCallBack, false);
img.src = image_url;

And then loadCallBackdraws an image.

The problem is that sometimes it image_urlrefers to a broken or nonexistent image. When this happens, I get a 404 error in the console, and the image on the canvas remains white. Instead, I would like to replace the image attribute with srcanother image_url.

I tried the following and it did not work:

img.addEventListener("error", function(){console.log("404");});

How can I identify 404s of images?

Note. I'm still looking for a solution, since none of the two published so far have worked.

+5
source share
2 answers

jQuery ... http://jsfiddle.net/5v2qG/

img = new Image(); 
$(img).bind('error', function () {
      alert('error called');                                                
});
img.src = "invalid_img_name.png";​
+4

, : jQuery javascript:

function brokenImage() { ... }

img = new Image();
img.onerror = brokenImage;
img.src = "invalid_img_name.png";​
+10

All Articles