DOMContentLoaded event in JavaScript

The DOMContentLoaded event can be used to tell when a page is fully loaded and ready to run scripts on the page; this may be useful if a script rely on dependencies that must be loaded for the script to work.

932 views

Edited: 2021-02-20 19:09

The DOMContentLoaded event only fires once the DOM has been fully loaded, without waiting for images, stylesheets, and subframes; if you also need assets to have finished loading, you should instead consider using the load event.

You can listen for this event on the Window interface.

You can setup an event listener that waits for this event to make sure that script dependencies are loaded and avoid undefined errors. When you setup an event listener, you will need to use a callback function that is executed once the event fires:

window.addEventListener('DOMContentLoaded', function() {
    document.getElementById("id_of_element").innerHTML = '<p>DOM fully loaded.</p>';
});

If you only want to update the text of an element, you could use innerText instead of innerHTML.

If you need to catch the event, pass it as a function argument:

window.addEventListener('DOMContentLoaded', function(event) {
  console.log(event);
});

If you are getting undefined errors on your dependencies, such as jQuery or $, then it may sometimes help to setup an event listener to make sure the DOM is loaded before you try to use such libraries.

Creating a ready(); function

It can be a good idea to create a ready function for the DOMContentLoaded event that you can call with a callback function that contains the code you want executed when the event fires, here is an example of how that might be done:

function ready(callback) {
  if (typeof callback !== 'function') {
    throw new Error('The callback parameter must be a function!'); 
  }
   window.addEventListener('DOMContentLoaded', callback);
}

In order to use this function you can use it with an anonymous arrow function:

let message = 'The DOM is fully loaded.';

ready(() => {
  console.log(message);
});

Or using the traditional function keyword:

ready(function() {
  console.log(message);
});

Tell us what you think:

  1. Some websites are blocking devtools with malicious JavaScript, so here is how to stop that without disabling JavaScript.
  2. We can not handle HTTP POST data from JavaScript, but we can still access the data while it is in the HTML form.
  3. getElementById should be used to select unique elements in a HTML document. Selected elements can be manipulated with JavaScript.
  4. Should you use querySelector or getElementById?; querySelector is more flexible, and able to perform more complex selections.
  5. the keydown event is not an ideal way to detect text-input by the user; instead you should consider using the input event.

More in: JavaScript Tutorials