How do you execute a JavaScript function automatically when a webpage loads? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you execute a JavaScript function automatically when a webpage loads?

message-square
0

To execute a JavaScript function automatically when a webpage loads, attach it to the DOMContentLoaded event (which fires once the HTML document is parsed and the DOM is ready, before images and stylesheets finish loading), load your script with <script type="module"> or <script defer>, or use window.addEventListener("load", ...) when you must wait for all external assets like images and frames to finish loading. For most UI setup code, DOMContentLoaded or defer / ES modules runs sooner and feels faster than waiting on load.


1. Running Code When the DOM Is Ready (DOMContentLoaded)

DOMContentLoaded triggers as soon as the browser finishes parsing the HTML markup into the DOM tree, making it ideal for querying elements and binding event listeners without waiting on large images or slow third-party media:

// Run initialization once HTML parsing completes
function initPage() {
  const banner = document.querySelector("#status-banner");
  if (banner) {
    banner.textContent = "Page ready";
  }
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initPage, { once: true });
} else {
  // Document already parsed if script ran late
  initPage();
}
  • Handles late-loaded scripts: Checking document.readyState !== "loading" ensures initPage() still runs even if the listener is attached after DOMContentLoaded has already fired.
  • Faster than load: Does not wait for images, videos, or stylesheets to finish downloading.

2. Using defer or <script type="module"> in HTML

Placing a standard blocking <script> in <head> before DOM elements exist can cause querySelector() calls to return null, whereas defer and type="module" download in parallel with HTML parsing and execute in order after the document is parsed:

<!-- In your HTML document: -->
<!-- <script src="/app.js" defer></script> -->
<!-- <script type="module" src="/main.js"></script> -->

// Inside defer or module script: DOM elements are already parsed
function bootApp() {
  const form = document.querySelector("#signup-form");
  if (!(form instanceof HTMLFormElement)) {
    return;
  }

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    console.log("Form handler active");
  });
}

bootApp();
  • Non-blocking HTML parsing: defer and type="module" do not block the HTML parser while fetching script files.
  • Strict mode & scoped variables: ES modules (type="module") run in strict mode by default and avoid polluting the global window scope.

3. Waiting for All Assets with window.addEventListener("load", ...)

Use window.addEventListener("load", ...) when your function depends on full layout dimensions, loaded images (img.complete), or external iframes—and avoid outdated inline attributes like <body onload="..."> that mix markup with logic and allow only one handler:

// Run after all images, stylesheets, and subresources finish loading
window.addEventListener(
  "load",
  () => {
    const images = Array.from(document.images);
    const allLoaded = images.every((img) => img.complete && img.naturalWidth > 0);
    console.log("All images loaded cleanly:", allLoaded);
  },
  { once: true }
);
  • Full resource readiness: Fires only after dependent assets finish loading, though slower networks can delay it.
  • Cleaner than onload attribute: addEventListener separates behavior from HTML and supports multiple independent listeners.

TL;DR: Use DOMContentLoaded (with a document.readyState check) or <script defer> / <script type="module"> to run JavaScript as soon as the DOM is ready, and use window.addEventListener("load", ...) only when you need all images and external resources finished first.