最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Detect whether Image is broken in Javascript - Stack Overflow

programmeradmin2浏览0评论

I'm adding images to an HTML5 canvas using Javascript:

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

And then loadCallBack draws the image.

The problem is that sometimes the image_url refers to a broken or nonexistent image. When this happens, I get a 404 error in the console and the image on the canvas stays white. Instead, I'd like to be able to replace the image's src attribute with another image_url.

I tried the following and it did not work:

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

How can I detect the 404s of the images?

Note: I'm still looking for a solution, as neither of the two posted so far has worked.

I'm adding images to an HTML5 canvas using Javascript:

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

And then loadCallBack draws the image.

The problem is that sometimes the image_url refers to a broken or nonexistent image. When this happens, I get a 404 error in the console and the image on the canvas stays white. Instead, I'd like to be able to replace the image's src attribute with another image_url.

I tried the following and it did not work:

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

How can I detect the 404s of the images?

Note: I'm still looking for a solution, as neither of the two posted so far has worked.

Share Improve this question edited Sep 6, 2012 at 21:03 LonelyWebCrawler asked Sep 6, 2012 at 20:00 LonelyWebCrawlerLonelyWebCrawler 2,9064 gold badges39 silver badges59 bronze badges 3
  • 1 The error event seems to work (in Chrome, at least): jsfiddle.net/qgJRF – bfavaretto Commented Sep 6, 2012 at 20:05
  • I've edited the title; Image() javascript class existed well before HTML5 (clarification). Since you mentioned canvas, I've left the HTML5 tag with your question. – Christian Commented Sep 6, 2012 at 20:11
  • But then it sounds like this question: stackoverflow.com/questions/92720/… – LonelyWebCrawler Commented Sep 6, 2012 at 20:14
Add a comment  | 

2 Answers 2

Reset to default 16

The same code as the Kostia's answer: just to compare the ugliness of jQuery and the beauty of vanilla javascript:

function brokenImage() { ... }

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

Works in jQuery for me... http://jsfiddle.net/5v2qG/

img = new Image(); 
$(img).bind('error', function () {
      alert('error called');                                                
});
img.src = "invalid_img_name.png";​
发布评论

评论列表(0)

  1. 暂无评论