DomContentLoaded event on image preview pages

DomContentLoaded event on image preview pages

  

For example I have some image src.

enter image description here

I open this page in the new chrome tab. On the page I have script that runs on DOMContentLoaded event:

 document.addEventListener('DOMContentLoaded', function() {
     console.log('done');/*call to init function*/
 }, false);

However in this case the event is never fire. On the regular page with full CSS and hierarchical DOM tree all works fine. Only in the case with open image alone in the new tab something goes wrong or I miss some details in using this event . Will be glad of any help or explanation

JSFIDDLE

UPDATE

According to this answer , the DOMContentLoaded event fires only on document.readyState=interactive, but the image view page never gave this status... So my question is there is any workaround of this issue?

Answer

The problem is in modern browsers images are loaded asynchronously, so the DOMContentLoaded event fires before the images are fully read in. Looking at your fiddle you don’t have a <html> or <body> elements, so I expect this is why you don’t get it at all, or it could be that their is so little content that it fires before you JS has time to run.

There are two possible work arounds to this issue.

ResizeObserver If you don’t predefined the size of the image, the element will resize as the images loads and you can detect this by adding a resizeObserver to the image element, or maybe even the body tag of the document if and only if the image is in the main document flow.

Load event of the image The image element has it’s own events for load and error and you could listen for these instead.

element.addEventListener('load', imageLoaded, false)
element.addEventListener('error', imageError, false)

This is going to be the more robust approach.

© 2024 Dagalaxy. All rights reserved.