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.
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.
Conclusion
See also: How JavaScript Works to learn more about JavaScript Runtime and DOM.
Created: September 03, 2022
Comments
There are no comments yet. Start the conversation!