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

addEventListener and the DOM

Rob Johnson

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
});
# commerce 14 # seo 5 # tools 6 # amazon 1 # sql 4 # shopify 9 # javascript 13 # projects 4 # css 2 # git 2 # php 3 # analytics 4 # api 6 # monitoring 2 # python 2 # aws 2