An image’s load handler in JavaScript answers a different question from an onload handler on the page body. The first reports the outcome for one image; the second corresponds to the window’s page-load event. Choose the event for the resource your code actually needs.
Listen Before Starting an Image Request
A JavaScript image onload handler runs when that image has loaded successfully. Attach both success and error listeners before assigning src, so a fast response does not finish before the listeners exist:
const img = new Image();
img.alt = "A mountain trail";
img.addEventListener("load", () => {
console.log("Intrinsic width:", img.naturalWidth);
document.body.append(img);
}, { once: true });
img.addEventListener("error", () => {
console.error("Image could not be loaded:", img.src);
}, { once: true });
img.src = "/images/trail.jpg";
Run this after document.body exists. A failed request or an unusable image triggers the error path; the successful handler does not run for that failure. Use the failure path to show a fallback or tell the user what happened. The image load callback in JavaScript can then focus on the successful result. If the source changes later, install handlers appropriate to the new request rather than assuming the first result applies to it.
Handle an Existing Image
An image already in the document may have finished before your script runs, including when it came from cache. Register listeners first, then check its current state. The following helper expects an image with a nonempty source already assigned and a source that will not change during the check:
function whenImageReady(img, onReady, onFailure) {
let settled = false;
function finish(ok) {
if (settled) return;
settled = true;
img.removeEventListener("load", loaded);
img.removeEventListener("error", failed);
if (ok) onReady(img);
else onFailure(img);
}
function loaded() { finish(true); }
function failed() { finish(false); }
img.addEventListener("load", loaded);
img.addEventListener("error", failed);
if (img.complete) finish(img.naturalWidth > 0);
}
const photo = document.querySelector("#photo");
whenImageReady(photo,
image => console.log("Ready:", image.currentSrc),
image => console.error("Failed:", image.currentSrc)
);
For this example, add an element such as <img id="photo" src="/images/trail.jpg" alt="A mountain trail"> to the document. The helper reports the current request once; it is not a subscription to later source changes. If you replace src or srcset, call it again for the new request and make sure stale results cannot update the interface for the previous image. Call it only after #photo exists. complete can also be true for a broken image or an image without a source, so it is not a success test alone. This helper treats a positive intrinsic width as success; use it for images expected to have intrinsic dimensions. The guard prevents a queued event from invoking the callback a second time. A JavaScript handler for an image’s onload event is useful for a pending request; the state check covers the already-finished case.
JavaScript Body Onload and DOM Readiness
The load event on window waits for the page’s dependent resources, including eager images, to finish loading. Lazy-loaded images are excluded, and page load does not imply that every individual resource succeeded. In JavaScript, body onload is an alias for the window load handler; prefer window.addEventListener("load", callback) when registering early, because it allows multiple listeners.
function initialize() {
console.log("DOM is ready");
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initialize, { once: true });
} else {
initialize();
}
For work that requires decoded pixels before insertion, img.decode() returns a promise that resolves after decoding and rejects if decoding fails. Handle that rejection separately. DOMContentLoaded fires after HTML parsing and deferred and module scripts have executed; it does not wait for images. The readiness check handles a script that arrives after that event. Similarly, attach a JavaScript body load listener before page load, or check document.readyState === "complete" when late initialization only needs to know that the page reached that state.
If image-dependent code runs with a width of zero or never runs on a repeat visit, inspect listener timing and the image’s complete and naturalWidth values. Handle both finished and pending images, and log the error event to distinguish a missed callback from a failed resource. If a body load callback in JavaScript waits longer than necessary, move DOM-only setup to the readiness pattern above.
