How do you wait for the DOM to be fully loaded before running JavaScript?
Run your code on the DOMContentLoaded event, add defer to the script tag, or place the script at the end of <body> so elements exist first.
Method 1: DOMContentLoaded event
document.addEventListener("DOMContentLoaded", () => {
// DOM is ready, safe to query elements
const button = document.querySelector("#myButton");
});
Method 2: Script at end of body
<body>
<button id="myButton">Click</button>
<!-- DOM elements exist when this runs -->
<script src="app.js"></script>
</body>
Method 3: defer attribute
<head>
<script src="app.js" defer></script>
</head>
| Event/Method | Waits for |
|---|---|
DOMContentLoaded |
HTML parsed |
load |
HTML + images + styles |
defer |
HTML parsed |
| End of body | Elements above script |
Tip: DOMContentLoaded is usually what you want - it doesn't wait for images.