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.
Use a capturing event listener on some parent DOM element like document
, document.body
or some other wrapper of images you need to observe. You can do this in the third argument of element's addEventListener
method:
document.body.addEventListener(
'load',
function(event){
var tgt = event.target;
if( tgt.tagName == 'IMG'){
tgt.style.display = 'inline';
}
},
true // <-- useCapture (or options object)
);
The third argument can be either boolean (true
) or newly added "options" object with a capture
boolean property ({ capture: true }
).
Using this approach, you don't have to (re-)attach event handlers while iterating through document.images
live HTMLCollection or some (re-)queried static NodeList.
This is generally known as "event delegation pattern".
It will also work for dynamically inserted images.
And same applies to image's error
loading events.
addEventListener
at MDN
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With