0

I know I can handle missing image error with jQuery like this:

$('img').on('error', function() {
    var $this = $(this);
    $this.attr('src', '/image-placeholder.svg');
});

This works just fine on page load. However, I have an Ajax call that returns HTML string to be placed on the page. The HTML also has images in it that might be missing. For the Ajax case the code above does not work: the missing resources are throwing 404 but they are not replaced by the placeholder. I tried to use event delegation, but no luck:

$(document).on('error', 'img', function() {
    var $this = $(this);
    $this.attr('src', '/image-placeholder.svg');
});

Is there a way to handle the missing resources after they've been returned via Ajax response?

My Ajax call uses the $.get() method.

lesssugar
  • 15,486
  • 18
  • 65
  • 115
  • Place your code in ajax success event right after set HTML. – Rahul Patel Sep 23 '16 at 10:45
  • Can you please share your ajax request code? – Rahul Patel Sep 23 '16 at 10:46
  • `$.ajax` `.error` handler is not handling 404? Maybe I've misunderstood the question. – Damaged Organic Sep 23 '16 at 10:46
  • Can you display your ajax call please. You might want to check the image exists..... maybe something like this will help you? http://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript unless its the ajax returning the 404 then you can use the error handler `.error` or `.fail` depending on your setup in your ajax call. – NewToJS Sep 23 '16 at 10:46
  • 1
    the load event does not bubble so you can't delegate the event – madalinivascu Sep 23 '16 at 10:49
  • As far as I know, the `.error()` and `.fail()` methods both indicate that the Ajax call *itself* failed (response code other than 200). My requests succeeds, but the problem lies in the returned HTML, as I wrote. – lesssugar Sep 23 '16 at 10:58
  • You can register a global handler for all image loading errors – Vladu Ionut Sep 23 '16 at 11:02

2 Answers2

1

The load event does not bubble so you can't delegate the event, you can bind the error event again after you appended the html to the page

madalinivascu
  • 32,064
  • 4
  • 39
  • 55
1

You can register a global handler for all image loading errors (you’ll need to use a capturing listener):

document.body.addEventListener(
    'error',
    function(event){
        var target = event.target;
        if( target.tagName == 'IMG'){
         console.log("your code here");
        }
    },
    true // <-- useCapture
)
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30