How do you make JavaScript code execute only after the page DOM has finished loading? | A1Lab@FahadM to JavaScriptEnglish • 5 days ago

How do you make JavaScript code execute only after the page DOM has finished loading?

message-square
0

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 after DOMContentLoaded has already fired (for example, injected dynamically or loaded late), a bare addEventListener("DOMContentLoaded", ...) listener will never fire.
  • DOMContentLoaded vs. load: Use DOMContentLoaded when querying or binding DOM elements; use window.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 as DOMContentLoaded: 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 for DOMContentLoaded (or using defer / type="module"), document.getElementById("btn") returns null if placed above the element. - Attaching DOMContentLoaded after the event already passed: Always check document.readyState when registering DOMContentLoaded in reusable modules or late-loaded scripts. - Confusing DOMContentLoaded with window.onload: window.onload / window.addEventListener("load", ...) waits for all media assets too, delaying UI setup unnecessarily. — TL;DR: Use document.addEventListener("DOMContentLoaded", fn)—paired with a document.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?