Sobes.tech
Junior

How to determine if the DOM is loaded?

sobes.tech AI

Answer from AI

Use the DOMContentLoaded event.

document.addEventListener('DOMContentLoaded', () => {
  // Code to execute after DOM is loaded
});

Alternatively, you can check the document.readyState property:

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    // Code
  });
} else {
  // DOM is already loaded
}

The DOMContentLoaded event fires after the HTML document has been fully loaded and parsed, but before external resources like styles and images are loaded.

To detect when the entire page, including all resources, has loaded, use the load event:

window.addEventListener('load', () => {
  // Code to execute after the entire page has loaded
});
How to determine if the DOM is loaded? — Frontend - sobes.tech