Skip to Content

How to Wait for the DOM Ready Event in JavaScript

In this tutorial, you'll learn how to wait for the DOM ready event in JavaScript.

Ad - Web Hosting from SiteGround - Crafted for easy site management. Click to learn more.
Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

What is the DOM?

The DOM, or Document Object Model, is a platform that allows web scripts to access and update content dynamically and in real-time without requiring synchronous page requests.

Detect When the DOM has Loaded

We'll need to wait until the DOM has loaded before we can access its content. We can do this by adding an event listener to the document object with the DOMContentLoaded event using JavaScript's built-in addEventListener() method in two ways.

The first way is with an arrow function:

document.addEventListener("DOMContentLoaded", (event) => {
// DOM is loaded

You can also use a traditional function:

document.addEventListener("DOMContentLoaded", function(event) {
// DOM is loaded

I generally prefer using traditional functions because you can access this unlike with arrow functions. In this case, this is the same as document, so you can use either method freely.

How the DOMContentLoaded Event Works

The DOMContentLoaded event fires once the document has completely loaded and processed all HTML contents and executed all available JavaScript functions. It does not wait for stylesheets to load.


See also: How JavaScript Works to learn more about JavaScript Runtime and DOM.

Posted by: Josh Rowe
Created: September 03, 2022


There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.