\n\n\nMethod 3: defer attribute\n\n \n\n\n\n\n\nEvent/Method\nWaits for\n\n\n\n\nDOMContentLoaded\nHTML parsed\n\n\nload\nHTML + images + styles\n\n\ndefer\nHTML parsed\n\n\nEnd of body\nElements above script\n\n\n\nTip: DOMContentLoaded is usually what you want - it doesn't wait for images.\n", "dateModified": "2026-07-14T16:25:27+00:00" } } }

LOGBOOK

HELP

Quiz Entry - updated: 2026.07.14

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.

From Quiz: WEBT / Frontend | Updated: Jul 14, 2026