How to prevent Javascript functions from running until the DOM is ready

addEventListener and the DOM

By Rob Johnson

Fri Apr 15 2022

#javascript

DOM stands for Document Object Model which describes the overall contents and layout of an HTML document.

If you declare JavaScript that targets an HTML element before it has been rendered, you'll get an error.

A simple way to wait until all the DOM is ready and loaded is to use an EventListener for the event DOMContentLoaded.

This way you can execute whatever Javascript you want after the DOM has finished rendering.

document.addEventListener('DOMContentLoaded', (event) => {
// stuff you want to run here
console.log('DOM fully loaded and parsed'); // show a message in the console
});

# tools 5 # sql 3 # javascript 10 # projects 4 # css 2 # git 2 # php 3 # analytics 4 # monitoring 2 # commerce 9 # seo 4 # api 3 # shopify 4 # python 2 # aws 2