Window: load event
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Theload event is fired when the whole page has loaded, including all dependent resources such as stylesheets, scripts (including async, deferred, and module scripts), iframes, and images, except those that areloaded lazily.This is in contrast toDOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.
This event is not cancelable and does not bubble.
Note:All events namedload will not propagate toWindow, even withbubbles initialized totrue. To catchload events on thewindow, thatload event must be dispatched directly to thewindow.
Note:Theload event that is dispatched when the main document has loadedis dispatched on thewindow, but has two mutated properties:target isdocument, andpath isundefined. These two properties are mutated due to legacy conformance.
To avoid running a script before the DOM it manipulates has been fully constructed, you can place the script at the end of the document body, immediately before the closing</body> tag, without wrapping it in an event listener. You should usually only use theload event to wait for external resources, such as images or deferred scripts, to load.
In this article
Syntax
Use the event name in methods likeaddEventListener(), or set an event handler property.
addEventListener("load", (event) => { })onload = (event) => { }Event type
A genericEvent.
Examples
Log a message when the page is fully loaded:
window.addEventListener("load", (event) => { console.log("page is fully loaded");});The same, but using theonload event handler property:
window.onload = (event) => { console.log("page is fully loaded");};Live example
HTML
<div> <button type="button">Reload</button></div><div> <label for="eventLog">Event log:</label> <textarea readonly rows="8" cols="30" ></textarea></div>body { display: grid; grid-template-areas: "control log";}.controls { grid-area: control; display: flex; align-items: center; justify-content: center;}.event-log { grid-area: log;}.event-log-contents { resize: none;}label,button { display: block;}#reload { height: 2rem;}JavaScript
const log = document.querySelector(".event-log-contents");const reload = document.querySelector("#reload");reload.addEventListener("click", () => { log.textContent = ""; setTimeout(() => { window.location.reload(true); }, 200);});window.addEventListener("load", (event) => { log.textContent += "load\n";});document.addEventListener("readystatechange", (event) => { log.textContent += `readystate: ${document.readyState}\n`;});document.addEventListener("DOMContentLoaded", (event) => { log.textContent += `DOMContentLoaded\n`;});Result
Specifications
| Specification |
|---|
| UI Events> # event-type-load> |
| HTML> # delay-the-load-event> |
Browser compatibility
See also
- DocumentreadyState API
- Related events: