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 in 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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!