Browser events: The `DOMContentLoaded` event

This is a very important event that we can listen for, to make sure the DOM is ready before interacting with it.

When the browser loads a Web page, once it finishes processing it, it fires the DOMContentLoaded event.

Sometimes you need to wait for this event before doing anything with the DOM, otherwise, your JavaScript would execute before the DOM is fully loaded in the browser memory. And things might be funny.

Here’s an example:


      document.addEventListener('DOMContentLoaded', () => {
        alert('the DOM is fully loaded!')




The DOMContentLoaded event fires when the DOM is fully loaded and you are sure you can interact with the DOM using JavaScript.

Typically you have 2 places to add JavaScript, in the head tag where it’s loaded as soon as possible and at the end of the body tag, where it’s loaded after the browser finished loading all the rest of the page content. Using DOMContentLoaded you are sure things are fully loaded before touching anything or adding events.

It’s like “tell me when you’re done so I can add my JavaScript”.

We’ll have a real-world example next week that talks about this specific problem.

Lessons this unit:

0: Introduction
1: Handling events
2: ▶︎ The `DOMContentLoaded` event
3: The `event` object
4: Mouse events
5: Keyboard events
6: `preventDefault()`
7: Stopping event propagation
8: Bubbling and capturing
9: Form submit event
10: Input fields events
11: Creating custom events