Is bubbling available for image load events?

2019-01-11 23:00发布

Can I use:

window.addEventListner();

in some way.

All my images have a display = 'none'.

Once the image has loaded,

I want to set display = 'inline'

This way I can normalize what is displayed while the image is being downloaded.

In this case, I can not pre-load my images.

5条回答
三岁会撩人
2楼-- · 2019-01-11 23:18
$('img').on('load', function() {
    $(this).show()
})

Without libraries:

window.onload = function() {
   var imgs = document.querySelectorAll('img')
   imgs.onload = function() {
      this.style.display = 'inline';
   }
}
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-11 23:19
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.

查看更多
聊天终结者
4楼-- · 2019-01-11 23:25

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.

查看更多
祖国的老花朵
5楼-- · 2019-01-11 23:30

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';
}
查看更多
你好瞎i
6楼-- · 2019-01-11 23:39

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

查看更多
登录 后发表回答