HTML onload Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onload attribute is an inline event handler that runs JavaScript when the load event fires — when a resource has finished loading. On <body onload="…"> or window.onload, that means the page and its subresources (images, stylesheets, etc.) are loaded. On <img>, <iframe>, or <script>, it fires when that specific element finishes loading. Use it to initialize UI, hide loading spinners, or read image dimensions. For “DOM is ready” (before all images), prefer DOMContentLoaded. Modern pages often use addEventListener("load", …) or defer on scripts instead of inline body onload.

What You’ll Learn

01

Event handler

Inline JS.

02

load event

Fully loaded.

03

body / window

Page ready.

04

img onload

Image ready.

05

addEventListener

Preferred way.

06

vs DOMContentLoaded

Timing.

Purpose of onload Attribute

The primary purpose of onload is to run code after loading completes. On a full page, that is when the browser has fetched the document and its dependent resources — so measurements that need rendered images or layout are safe. On an individual <img>, you can swap a placeholder for the real picture or show width and height once the file arrives.

Many apps only need the HTML parsed, not every image — in that case DOMContentLoaded fires earlier and feels snappier. Choose load when you truly depend on all subresources being ready.

💡
body onload vs window load

In HTML documents, <body onload> sets the window’s load handler. window.addEventListener("load", fn) is the modern equivalent.

📝 Syntax

Set onload on body, img, iframe, or assign window.onload:

onload.html
<body onload="onPageLoad()">
  <!-- page content -->
</body>

<img src="photo.jpg" alt="Photo" onload="imageReady(this)">

Syntax Rules

  • Value is JavaScript executed when the load event fires on that element.
  • body onload / window.onload — entire page and subresources loaded.
  • img onload — that image file loaded (also fires for cached images).
  • iframe onload — embedded document loaded.
  • Modern alternative: window.addEventListener("load", handler).
  • Does not fire if the resource fails — use onerror for failures.
  • The load event does not bubble from window in the same way as clicks — attach to the target you care about.

💎 Values

The onload attribute accepts a string of JavaScript code or function reference:

  • onload="onPageLoad()" — Call a named function when the page loads.
  • onload="imageReady(this)" — Pass the loaded element.
  • JavaScript: window.onload = function() { … }.
onload-js.html
window.addEventListener("load", () => {
  document.getElementById("loader").hidden = true;
  initDashboard();
});

document.addEventListener("DOMContentLoaded", () => {
  // DOM ready — images may still be loading
  wireUpButtons();
});

⚡ Quick Reference

Targetload fires whenCommon use
body / windowPage + subresources loadedHide loader, full init
imgImage file loadedReveal image, read size
iframeEmbedded doc loadedResize iframe, postMessage
HTML parsed onlyNo (use DOMContentLoaded)Faster DOM setup
Resource failedNoUse onerror
Handler attributeonloadInline on element

Applicable Elements

TargetSupported?Notes
<body>YesClassic page load hook
window (via script)YesRecommended registration
<img>YesPer-image load
<iframe>YesEmbedded page load
<script>, <link rel="stylesheet">YesResource load (rare inline use)
<input>NoNot a loadable resource element

load vs DOMContentLoaded vs defer

ApproachWhen code runsTypical use
onload / loadAll page resources loadedNeeds images/layout ready
DOMContentLoadedHTML parsedWire up DOM early
<script defer>After parse, before loadModern script loading

Examples Gallery

Page init on body load, addEventListener on window, and image onload feedback.

👀 Live Preview

This tutorial page already fired load — status below was set when resources finished:

Checking load state…

Example — body onload page init

Run setup when the full page has loaded:

body-onload.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Onload Example</title>
</head>
<body onload="onPageLoad()">
  <p id="status">Loading…</p>

  <script>
    function onPageLoad() {
      document.getElementById("status").textContent =
        "Page loaded successfully!";
    }
  </script>
</body>
</html>
Try It Yourself

How It Works

The browser fires load on the window after the document and its resources finish loading. The inline body onload handler runs your init function once.

Dynamic Values with JavaScript

Attach the page load handler with addEventListener:

dynamic-onload.html
<script>
  window.addEventListener("load", function () {
    console.log("Page load handler executed!");
    document.getElementById("app").classList.remove("loading");
  });

  // Legacy property form:
  document.body.onload = function () { /* … */ };
</script>
Try It Yourself

How It Works

Register once in a script. The callback runs a single time when the page load completes.

Example — img onload

Show feedback when an image finishes loading:

img-onload.html
<img src="/images/codetofun-logo.png" alt="Logo"
  onload="imageReady(this)">
<p id="imgStatus"></p>

<script>
  function imageReady(img) {
    document.getElementById("imgStatus").textContent =
      "Loaded " + img.naturalWidth + "×" + img.naturalHeight + " px";
  }
</script>
Try It Yourself

How It Works

Each image fires its own load event. Use this or the parameter to read naturalWidth and naturalHeight after decode.

♿ Accessibility

  • Do not block with alert() — Show load status in the page, not a blocking dialog.
  • Announce ready state — Use aria-busy="false" when loading finishes on dynamic regions.
  • Images need alt textonload does not replace accessible alt attributes.
  • Avoid long main-thread work — Heavy init on load delays interaction for all users.
  • Loading indicators — Hide spinners when load completes so screen readers see final content.

🧠 How onload Works

1

Browser fetches page

HTML, CSS, images.

Network
2

Resources finish

Parse + download.

Ready
3

load fires

onload handler runs.

Event
=

App initialized

UI, charts, images ready.

Browser Support

The load event and onload handler are supported in all modern browsers on window, body, img, and iframe.

DOM Events · Fully supported

Universal onload support

All major browsers fire load on the window and on loadable elements.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onload attribute 99% supported

Bottom line: Reliable everywhere; prefer addEventListener("load") and DOMContentLoaded when appropriate.

💡 Best Practices

✅ Do

  • Use DOMContentLoaded when you only need the DOM tree
  • Use load when images or iframes must be ready first
  • Prefer window.addEventListener("load", …) over inline body onload
  • Pair img onload with onerror for robust media handling
  • Keep load handlers fast — defer heavy work with requestIdleCallback if needed

❌ Don’t

  • Use alert() on every page load
  • Wait for load when DOMContentLoaded is enough
  • Put large scripts inline in onload strings
  • Assume load fires again on SPA route changes — it does not
  • Block rendering with slow synchronous init in the load handler

Conclusion

The onload attribute runs JavaScript when loading finishes — on the full page via body / window, or on individual resources like images and iframes.

Prefer addEventListener("load", …), use DOMContentLoaded when you do not need every asset, and show user feedback without blocking alerts.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onload

Bookmark these before wiring page and resource load handlers.

5
Core concepts
🖼 02

body / window

Page init.

Scope
🔄 03

DOMContentLoaded

Earlier hook.

Compare
🖼 04

img onload

Per resource.

Pattern
05

addEventListener

Modern way.

API

❓ Frequently Asked Questions

It runs JavaScript when the load event fires — when a page or element has finished loading its resource(s).
Prefer window.addEventListener("load", handler). Inline body onload works for learning and simple pages.
DOMContentLoaded = HTML parsed. load = full page including images and other subresources.
Yes. img onload runs when that image file has loaded successfully.
No — use onerror for failed resource loads.
Yes in all modern browsers; Internet Explorer 9+.

Master page and resource load events

Practice the onload attribute with body init and image load examples in the Try It editor.

Try onload demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful