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