Lifecycle DOM Events

From the moment a web page starts to load in the browser until the user exits the page, a few useful DOM events happen. We can hook into these events to run functions. The most useful of these events are:

  • DOMContentLoaded
  • load

DOMContentLoaded Event

DOMContentLoaded is one of the most useful page lifecycle events. It happens on the document object and it fires when

  • HTML is parsed
  • DOM tree is built
  • Synchronous JavsScript scripts are loaded and executed

Note that the DOMContentLoaded event doesn’t wait for CSS files or images to load. It kinda makes sense, because JavaScript is able to change the DOM (add, remove or change DOM elements) so the scripts should be executed before DOM is ready. On the other hand, CSS files or images don’t change the DOM so the DOMContentLoaded event won’t wait for them.

Keep in mind that script tags with defer attribute will block the DOMContentLoaded event (they have to be executed before the event), but script tags with async attribute won’t block the DOMContentLoaded event (they may be executed before or after the event).

This is the basic syntax

document.addEventListener(‘DOMContentLoaded’, (event) => {
console.log(‘DOM fully loaded and parsed’);

Load Event

The load event happens on the window object (not document) and is fired when all resources (including the CSS files and images) are loaded.

This is the base syntax

window.addEventListener(‘load’, (event) => {
console.log(‘page is fully loaded’);

In this article, we had a look at two of the most common page lifecycle DOM events.