JavaScript DOMContentLoaded event and Anonymous functions



The DOMContentLoaded event

We mentioned the DOMContentLoaded event in the list of common JavaScript events, but it's important enough to warrant its own section. This event runs when all the HTML tags on the page have been processed, and the DOM is fully ready to be accessed by JavaScript.

We haven't needed to use this event so far because we put all of our JavaScript code at the bottom of the page, and all the HTML tags above the JavaScript had already been processed. However, it's a good idea to only run your code when this event fires. That way your JavaScript code can be included anywhere on the page without errors.

Running your code when the DOM is ready

function afterDomReady() {
    // Normal JavaScript code goes here

// Run afterDomReady function when the DOM is ready
document.addEventListener('DOMContentLoaded', afterDomReady);

Anonymous functions

Using anonymous functions as event handlers

It's also common to use anonymous functions (functions without a name) when creating the function to handle an event.


// Run anonymous function when the DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    // Normal JavaScript code goes here

This code works exactly the same as the previous example. In this code, instead of passing a function name, we define the function right there. The only difference is the function doesn't have a name. When the DOMContentLoaded event fires, it will run this function.

Anonymous functions are useful when you only need a function once and won't need to call it anywhere else.

JavaScript Practice Problems

Below, you'll find a list of all the JavaScript practice problems from this tutorial (in case you didn't do them earlier).

Leave a Comment