paint-brush
DOM Readiness in Javascriptby@smpnjn
188 reads

DOM Readiness in Javascript

by Johnny SimpsonOctober 18th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The Javascript is loading before the DOM, so it is not ready to attach events to your HTML. This is a pretty common problem related to DOM readiness - your HTML isn't ready to have Javascript applied to it. If you want to wait for the DOM to load, then try using `DOMContentLoaded`. That means you can continue to have your Javascript before your HTML, and encounter no issues. Of course, you can also solve this problem by putting your Javascript **after** your HTML - but this is not always possible.
featured image - DOM Readiness in Javascript
Johnny Simpson HackerNoon profile picture


When you're working with Javascript, you're likely to have run into a pretty common problem: if your Javascript appears before your HTML, then trying to do things like attach events to your HTML is not possible. For example, consider this code:


<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
            document.querySelector('#button').addEventListener('click', () => {
                console.log('You clicked me!')
            });
        </script>
    </head>
    <body>
        <button id="button">Click Me</button>
    </body>
</html>


Even though there is a button with the ID #button, this code actually throws an error. The reason why is that the Javascript is loading before the DOM. Therefore trying to query select for #button returns null:


Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at file.html:5:46


This is a pretty common problem related to DOM readiness - your HTML DOM has not loaded - so it is not ready to have Javascript applied to it.

Waiting for the DOM to be ready in Javascript

If you want to wait for the HTML to load, before your Javascript runs - then try using DOMContentLoaded. We can wrap our entire Javascript in this event listener like so:


window.addEventListener('DOMContentLoaded', () => {
    document.querySelector('#button').addEventListener('click', () => {
        console.log('You clicked me!')
    });
});


Now, no error will be produced in your code, since the code within the DOMContentLoaded event listener will only fire once the HTML is fired. That means you can continue to have your Javascript before your HTML, and encounter no issues. Of course, you can also solve this problem by putting your Javascript after your HTML - but this is not always possible.

I hope you've enjoyed this quick guide to DOM Readiness and DOMContentLoaded in Javascript.



Also published here.