2

I have the following function as a fallback when the URL of the image returns 404. The function should happen after the AJAX. So when AJAX is made, and the URL returns 404, the image will replace the broken image. This functions works in Safari and Firefox, but not in Chrome.

When it's not working in Chrome, the console says:

imageOnError is not defined.

    function imageOnError(img) {
       img.onerror = ' ';
       img.src = "http://v.images.boldride.com/vorsteiner/2012/vorsteiner-bmw-m3-gts5.1471x972.Jul-11-2012_13.02.33.232886.jpg";
       return true;
    }

Any ideas what's going on with it?

Here is the JSFiddle

7537247
  • 303
  • 5
  • 19

2 Answers2

0

When browser gets this:

<img src="http://ip.dlron.us/img.jpg"
     onerror="return imageOnError(this);">

the image's URL may already be tested against existence (and result cached) and so browser can tell right away that image is not available and call your onerror handler.

Thus your imageOnError(img) implementation shall appear in HTML before first image that uses it.

c-smile
  • 26,734
  • 7
  • 59
  • 86
  • It seems to be the problem, but the page(image content) gets generated by both AJAX and HTML. – 7537247 Feb 22 '16 at 22:29
  • Could you elaborate more on "page(image content)" and "image content gets generated by both AJAX and HTML" ? – c-smile Feb 22 '16 at 22:39
  • I think the issue has something to do with the AJAX call, maybe because when AJAX renders the content, the `imageOnError function` wasn't ready or something. – 7537247 Feb 22 '16 at 23:54
0

I ended up using jQuery to solve this problem. It actually works better than calling onerror event directly on markup. Thanks everyone's help.

$(errorImage).on('error', function(){
  $(this).attr('src', 'broken-image-url');
});
7537247
  • 303
  • 5
  • 19