How do you run a JavaScript function immediately once the DOM is ready? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you run a JavaScript function immediately once the DOM is ready?

message-square
0

To run a JavaScript function as soon as the HTML document is parsed and the DOM tree is ready—without waiting for slow images, stylesheets, or external frames—listen for "DOMContentLoaded" on document, and check document.readyState !== "loading" first so your callback still runs immediately if that event has already fired. Using <script type="module"> or <script defer> also defers execution until parsing finishes, while a guarded runOnDomReady(callback) helper handles both early and late script execution reliably.


1. Running a Function Safely with DOMContentLoaded and document.readyState

Registering a "DOMContentLoaded" listener after the event has already occurred leaves a plain listener uncalled; checking document.readyState guarantees immediate execution when the DOM is already interactive or complete:

// Execute callback immediately if DOM is already ready, or on DOMContentLoaded otherwise
function runOnDomReady(callback) {
  if (typeof callback !== "function") {
    throw new TypeError("Expected callback to be a function.");
  }

  if (document.readyState !== "loading") {
    callback();
    return;
  }

  document.addEventListener("DOMContentLoaded", callback, { once: true });
}

// Example usage:
runOnDomReady(() => {
  const badge = document.querySelector("#ready-badge");
  if (badge) {
    badge.textContent = "DOM ready";
  }
});
  • "DOMContentLoaded" vs. "load": "DOMContentLoaded" fires once initial HTML parsing finishes; window.addEventListener("load", ...) waits until images, media, and subframes finish downloading.
  • Late-loaded script protection: Checking document.readyState !== "loading" ensures dynamically injected or late-running scripts still execute callback.

2. Module and defer Scripts vs. DOMContentLoaded

In modern HTML, <script type="module"> and classic <script defer> tags are deferred until HTML parsing completes and run in document order just before "DOMContentLoaded":

<!-- HTML: module and deferred scripts run after DOM elements are parsed -->
<script type="module" src="/js/main.js"></script>
<script src="/js/toolbar.js" defer></script>

// Inside /js/main.js (ES module): DOM nodes above the script already exist
const appRoot = document.querySelector("#app");
console.log(Boolean(appRoot)); // true when #app appears earlier in the HTML
  • type="module" is deferred automatically: ES module scripts do not block HTML parsing and run once the document is parsed.
  • Avoid async for DOM order: <script async> executes as soon as fetched—potentially before "DOMContentLoaded" and before later DOM elements exist.

3. Guarding Initialization Logic Inside a Dedicated Function

Keep startup code inside a focused helper that checks for target DOM nodes and catches unexpected errors so one missing widget does not break page initialization:

// Initialize a DOM widget safely without mutating external state
function initSearchBox(selector = "[data-search-input]") {
  const inputEl = document.querySelector(selector);
  if (!(inputEl instanceof HTMLInputElement)) {
    return false;
  }

  inputEl.dataset.initialized = "true";
  return true;
}

runOnDomReady(() => {
  try {
    initSearchBox();
  } catch (error) {
    console.error("DOM initialization error:", error);
  }
});
  • Guard element lookups: Always verify that document.querySelector() returns the expected element before reading or updating attributes or properties.
  • Prefer declarative/event listeners over inline handlers: Keep behavior in JS modules or runOnDomReady() rather than inline onload attributes.

TL;DR: Check if (document.readyState !== "loading") fn(); else document.addEventListener("DOMContentLoaded", fn, { once: true }); so your function runs immediately once the DOM is parsed—whether before or after "DOMContentLoaded" has already fired.