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

javascript - How to listen to the error event of all images? - Stack Overflow

programmeradmin0浏览0评论

I want to hide broken images that get loaded dynamically. For static ones, this works.

$('img').error(function() {
    $(this).css({ 'visibility': 'hidden' });
});

However, when I bind that to the document nothing happens. There is no error in the console, either.

$(document).on('error', 'img', function() {
    $(this).css({ 'visibility': 'hidden' });
});

How can I listen to errors of images that are loaded dynamically?

I want to hide broken images that get loaded dynamically. For static ones, this works.

$('img').error(function() {
    $(this).css({ 'visibility': 'hidden' });
});

However, when I bind that to the document nothing happens. There is no error in the console, either.

$(document).on('error', 'img', function() {
    $(this).css({ 'visibility': 'hidden' });
});

How can I listen to errors of images that are loaded dynamically?

Share Improve this question edited Apr 2, 2016 at 0:19 Chad 1,5493 gold badges21 silver badges46 bronze badges asked Mar 19, 2014 at 8:58 danijardanijar 34.2k53 gold badges176 silver badges315 bronze badges 2
  • 3 it is because the error event does not bubbles.. and delegated handler such as the one you have tried depends on the event being bubbled to the ancestor document element – Arun P Johny Commented Mar 19, 2014 at 9:01
  • possible duplicate of Jquery on image error not working on dynamic images? – Zword Commented Mar 19, 2014 at 9:01
Add a comment  | 

2 Answers 2

Reset to default 13

You can do it with the useCapture of addEventListener.

document.addEventListener('error', (e) => {
  // do your magic here
}, true)

The error event does not bubble. The DOM Level 2 Events specifies it should but The DOM Level 3 Events overrides this.

You could try window.onerror but I'm not sure if that only catches run-time script errors in your code or errors thrown by failing resources. If it works it will also catch all errors.

Arun P Johny confirms my doubts, window.onerror is a no-go.

The matter is discussed in error event with live.

A solution could be to add a generic error handler on all images, those loaded dynamicly included. And then have that generic error handler trigger a custom jQuery event, e.g.:

$( document ).on( 'imgerror', function ( event, originalEvent ) {
    // originalEvent is the error event
} );

function genericImgOnError( event ) {
    $( event.target ).trigger( 'imgerror', event );
}

function getImg( src ) {
    return $( '<img/>', {
        src: src,
    } ).on( 'error', genericImgOnError );
}
发布评论

评论列表(0)

  1. 暂无评论