lesssugar
lesssugar

Reputation: 16181

Handling missing image resources during Ajax call

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.

Upvotes: 0

Views: 149

Answers (2)

Vladu Ionut
Vladu Ionut

Reputation: 8193

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
)

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

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

Upvotes: 1

Related Questions