nonopolarity
nonopolarity

Reputation: 150996

Isn't it possible that when we add the event handler for DOM Ready, it is too late?

Theoretically, isn't true that our code can add the event listener for DOM Ready, but when we add it, it is already too late?

For example, if we link to a .js file near the end of the <body> ... </body>, and the download time of that .js file is 2 or 3 seconds later, and the DOM has long been ready and the event already fired and all listeners notified, and now the JS code does

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM Ready event fired');
});

and it really is too late now, and the handler will never get called? In practice, it does not and should not happen, because then there would be weird behaviors. So how is this handled? Does the browser "retroactive" notify the listeners (even though the listener was added too late, the browser will notify it?).

Having said that, the "browser will notify the listener even if added too late" isn't true, if we register the DOM ready listener inside of the DOM ready handler:

window.addEventListener('DOMContentLoaded', (event) => {
  console.log('DOMContentLoaded event fired 01');
  window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM Ready event fired 02');
  });
});

Another way is when we load a page, and then in the debug console, type in

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM Ready event fired');
});

It is even true that if we missing the current event cycle, then it won't be called:

setTimeout(function() {
  window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM Ready event fired');
  });
}, 0);

So what is the rule about if the listener is added too late?

Upvotes: 2

Views: 1334

Answers (1)

Barmar
Barmar

Reputation: 780974

No, this isn't a problem.

The DOMReady event isn't triggered until all the HTML is loaded, which includes loading all the scripts. The exception is scripts with the async attribute; these are loaded in the background, and DOMReady doesn't wait for them. Scripts with the defer attribute are also loaded in the background, but the browser waits for them to load before sending the DOMReady event.

And if you use jQuery, you can use its .ready() function even after the DOM is loaded. If you call $(document).ready() later, it simply calls the function immediately, rather than adding an event listener.

See Scripts: async, defer for an explanation of synchronous versus asynchronous loading of scripts.

Upvotes: 1

Related Questions