References

Beginner-friendly references for web development, with live, editable examples.

The HTML onload event

Event All modern browsers Updated
Quick answer

The HTML onload attribute runs JavaScript when an element or the page and its resources finish loading. It is an inline handler for the load event; in modern code prefer addEventListener('load', …).

Overview

The onload event attribute runs JavaScript when the element or page finishes loading. In JavaScript the event itself is named load — drop the on prefix when you call addEventListener.

It is a resource-loading event, fired as the page or an individual resource (an <img>, <script>, <iframe> or the document) loads, fails or is aborted.

You can wire this up with the inline onload HTML attribute, but the modern, recommended approach is element.addEventListener('load', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<element onload="handler()">…</element>

element.addEventListener('load', handler);

Best practices

  • Prefer element.addEventListener('load', handler) over the inline onload attribute — it separates behavior from markup and allows multiple handlers.
  • Use it to react to load success or failure — for example showing a fallback when an image fails.
  • Attach it before the resource starts loading so you do not miss an early event.
  • For the window load, prefer deferring non-critical work rather than blocking on it.

Frequently asked questions

What is the onload event?
It runs JavaScript when the element or page finishes loading. In JavaScript the event is named load.
When does this event fire?
As a resource or the page finishes loading, fails to load, or has its loading aborted.
How do I handle an image that fails to load?
Listen for the error event on the <img> and swap in a fallback.
Should I use the onload attribute or addEventListener?
Prefer addEventListener('load', …) in JavaScript. The inline onload attribute works but mixes behavior into the markup and allows only one handler per element.