What is the vanilla JavaScript equivalent of jQuery's $(document).ready()? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

What is the vanilla JavaScript equivalent of jQuery's $(document).ready()?

message-square
0

The vanilla JavaScript equivalent of jQuery’s $(document).ready(fn) is listening for the "DOMContentLoaded" event on document, while also checking document.readyState !== "loading" so fn still runs immediately if the DOM has already finished parsing before your listener attaches. Whereas jQuery’s $(document).ready() safely runs callbacks immediately when registered after the DOM is ready, a bare document.addEventListener("DOMContentLoaded", fn) alone will not fire if "DOMContentLoaded" has already passed.


1. Direct Equivalent with DOMContentLoaded and document.readyState

Pair document.readyState !== "loading" with document.addEventListener("DOMContentLoaded", fn, { once: true }) to match $(document).ready(fn) behavior across both early and late script execution:

// Vanilla JS equivalent of jQuery's $(document).ready(callback)
function onDocumentReady(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:
onDocumentReady(() => {
  const statusEl = document.querySelector("#app-status");
  if (statusEl) {
    statusEl.textContent = "Ready";
  }
});
  • Matches jQuery’s late-binding behavior: Like $(document).ready(fn), checking document.readyState ensures callback still runs when attached after "DOMContentLoaded".
  • Fires before external media finishes: Like $(document).ready(), "DOMContentLoaded" runs once HTML parsing completes, before heavy images or iframes finish loading.

2. Comparing $(document).ready(), DOMContentLoaded, defer, and window.load

Choose the timing hook that matches your HTML structure and whether you need external assets to finish downloading:

// Non-mutating helper summarizing readyState values in vanilla JS
function describeReadyState(state = document.readyState) {
  if (typeof state !== "string") {
    throw new TypeError("Expected state to be a string.");
  }

  const descriptions = {
    loading: "Document is still parsing HTML.",
    interactive: "Document parsing finished; DOM is ready, subresources still loading.",
    complete: "Document and all subresources (images, styles, frames) have finished loading."
  };

  return descriptions[state] ?? "Unknown document.readyState value.";
}

// Example usage:
console.log(describeReadyState("interactive"));
// "Document parsing finished; DOM is ready, subresources still loading."
  • "DOMContentLoaded" vs. "load": window.addEventListener("load", ...) (equivalent to jQuery’s $(window).on("load", ...)) waits until all images, stylesheets, and frames finish loading.
  • <script defer> or <script type="module">: Modern script tags with defer or type="module" execute after HTML parsing is complete—often eliminating the need for a wrapper in external scripts.

3. Handling Edge Cases Safely in Vanilla JS

Avoid calling callbacks synchronously inside an unhandled loop or assuming document exists outside browser environments, and guard DOM lookups before manipulating elements:

// Safely invoke a ready callback and guard against missing DOM nodes
function runSafeReadyTask(taskFn) {
  if (typeof taskFn !== "function") {
    throw new TypeError("Expected taskFn to be a function.");
  }

  if (typeof document === "undefined") {
    return false;
  }

  onDocumentReady(() => {
    try {
      taskFn(document);
    } catch (err) {
      console.error("Error running DOM ready task:", err);
    }
  });

  return true;
}

// Example usage:
runSafeReadyTask((doc) => {
  const root = doc.querySelector("#root");
  if (root) {
    root.dataset.ready = "true";
  }
});
  • No jQuery dependency needed: Vanilla document.readyState + "DOMContentLoaded" works natively in all modern browsers with zero extra library overhead.
  • Guard against missing elements: document.querySelector() returns null when no element matches, so always check before accessing properties or methods.

TL;DR: Use if (document.readyState !== "loading") fn(); else document.addEventListener("DOMContentLoaded", fn, { once: true }); as the vanilla JavaScript equivalent of jQuery’s $(document).ready(fn).