Is bubbling available for image load events?

纵饮孤独 提交于 2019-11-27 14:38:32

The load/onload event does not bubble (reference, reference), so what you're asking for is not possible. You'll have to attach an event handler to each image node, or intercept the event during the capture phase, as suggested in other answers.

Use capturing event listener on some DOM node other than window (body or other parent of image elements of interest):

document.body.addEventListener(
    'load',
    function(event){
        var tgt = event.target;
        if( tgt.tagName == 'IMG'){
            tgt.style.display = 'inline';
        }
    },
    true // <-- useCapture
)

With this you don't have to (re)attach event handlers while iterating through document.images.

And this will work for dynamically inserted images as well.

Same is true for image's error loading events. MDN: addEventListener

Array.prototype.forEach.call(document.querySelectorAll('img'), function (elem) {
    elem.addEventListener('load', function () {
        this.style.display = 'inline';
    });
    if (elem.complete) {
        elem.style.display = 'inline';
    }
});

The "load" event will not trigger if the image is incidentally loaded already; thus, we check whether complete is already set.

$('img').on('load', function() {
    $(this).show()
})

Without libraries:

window.onload = function() {
   var imgs = document.querySelectorAll('img')
   imgs.onload = function() {
      this.style.display = 'inline';
   }
}

You can use the Image.onload event handler but there's no bubbling involved.

var i = new Image;
i.onload = function() {
  this.style.display = 'block';
}

Since the load event does not bubble, you can lauch your own bubbling event. An example with jQuery:

<img src="dog.jpg" onload="$(this).trigger('image-loaded')" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!