Hiprup

What is the difference between load and DOMContentLoaded events?

Two events that fire at different points in page loading.

  • DOMContentLoaded — fires when the HTML is parsed and the DOM is ready, before images/styles finish. Earlier.

  • load — fires when everything is loaded: images, stylesheets, fonts, subframes. Later.

For most scripts: DOMContentLoaded is the right time to run — no need to wait for images.

// DOMContentLoaded — DOM ready, resources may still load
document.addEventListener('DOMContentLoaded', () => {
  console.log('DOM ready!');
  document.querySelector('#app').textContent = 'Loaded';
  // Images may still be loading
});

// load — everything including images/CSS loaded
window.addEventListener('load', () => {
  console.log('Everything loaded!');
  // Safe to read image dimensions
  const img = document.querySelector('img');
  console.log(img.naturalWidth, img.naturalHeight);
});

// Modern alternative: defer attribute on script
// <script src="app.js" defer></script>
// Script runs after DOM is parsed (like DOMContentLoaded)
// No need for DOMContentLoaded listener

DOMContentLoaded fires earlier — HTML parsed, DOM ready. load fires later — all resources complete. For most JS initialization, DOMContentLoaded is sufficient.

The defer attribute on <script> is the modern alternative — the script runs after DOM parsing without needing an event listener.

DOMContentLoaded = DOM ready (earlier, faster). load = everything loaded (later, including images). Use DOMContentLoaded for DOM manipulation.

Mention defer attribute as the modern alternative (no event listener needed).