To run JavaScript only after the DOM is ready, listen for the DOMContentLoaded event (document.addEventListener("DOMContentLoaded", ...)), handle the case where the DOM is already loaded (document.readyState !== "loading"), or use jQuery’s ready shortcut ($(function () { ... })). For external scripts, placing <script defer src="..."></script> or <script type="module" src="..."></script> in the document is also a clean way to defer execution until parsing finishes.
1. Vanilla JavaScript (DOMContentLoaded and readyState)
DOMContentLoaded fires as soon as the initial HTML document is completely parsed and the DOM tree is built—without waiting for stylesheets, images, or subframes to finish downloading.
function initApp() {
console.log("DOM is ready:", document.querySelectorAll("button").length);
}
// Run immediately if the DOM already finished loading, otherwise wait for DOMContentLoaded
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initApp, { once: true });
} else {
initApp();
}
- Why check
document.readyState: If a script runs afterDOMContentLoadedhas already fired (for example, injected dynamically or loaded late), a bareaddEventListener("DOMContentLoaded", ...)listener will never fire. DOMContentLoadedvs.load: UseDOMContentLoadedwhen querying or binding DOM elements; usewindow.addEventListener("load", ...)only when you need all images, fonts, and external resources completely loaded.
2. Using jQuery Ready ($(function () { ... }))
If jQuery is already loaded on the page, $(function () { ... }) (shorthand for $(document).ready(...)) waits until the DOM is ready and also runs immediately if the DOM is already ready.
$(function () {
console.log("jQuery DOM ready");
$("#status-banner").fadeIn(200);
});
- Order matters: Make sure jQuery is loaded before any code calling
$. - Same timing asDOMContentLoaded: jQuery’s ready callback fires once the DOM is parsed, before slow images finish loading. — ## 3. Common Traps to Avoid - Querying DOM elements in a top-level<script>before elements exist: Without waiting forDOMContentLoaded(or usingdefer/type="module"),document.getElementById("btn")returnsnullif placed above the element. - AttachingDOMContentLoadedafter the event already passed: Always checkdocument.readyStatewhen registeringDOMContentLoadedin reusable modules or late-loaded scripts. - ConfusingDOMContentLoadedwithwindow.onload:window.onload/window.addEventListener("load", ...)waits for all media assets too, delaying UI setup unnecessarily. — TL;DR: Usedocument.addEventListener("DOMContentLoaded", )—paired with adocument.readyState !== "loading"check so late scripts still run—or$(function () { fn(); })in jQuery to run code once the DOM is ready.
Are you writing vanilla JavaScript or jQuery, and do you need to wait only for the DOM tree (DOMContentLoaded) or for images and external assets (load) as well?
