DEV Community

Cover image for Waiting for the DOM to be ready in Javascript
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

16

Waiting for the DOM to be ready in Javascript

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>
Enter fullscreen mode Exit fullscreen mode

Even though there is a button with the ID #button, this code actually throws an error. The reason why is because 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
Enter fullscreen mode Exit fullscreen mode

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!')
    });
});
Enter fullscreen mode Exit fullscreen mode

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (3)

Collapse
 
thi3rry profile image
Thierry Poinot

You can also put JavaScript at the end of the page to optimize your webperf if you don't rely on full js framework.
This way you can query elements int the DOM without waiting it is fumly loaded. It can speedup the rendering of your page

Collapse
 
smpnjn profile image
Johnny Simpson

Correct, actually it's typically better to do what you said, but I did briefly mention that you can do that too :)

Collapse
 
adebanjo_ogunseye_dfc4eaa profile image
Adebanjo Ogunseye

I have this issue to deal with even when script is at the end of my html body tag.
When the page load to renders.it render in flash millisecond and disappear. could it be the addEventListener method. It render in console but not in the browser...could you help to resolve this irritating issue ?

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more