Events
onload
A resource loads successfully, or Window finishes its initial load lifecycle. HTML event-handler content attribute or corresponding event-handler property; the event fires only on relevant targets. The example uses document.getElementById("demo"). Event interface: Event. For the described native event: bubbles: no; cancelable: no. For the page, load waits for dependent resources except certain lazy-loaded items; DOMContentLoaded is earlier. Example: The image source is set after the listener is registered. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.
Formal Syntax & Structure
html syntaxhtml
<img onload="handleEvent(event)">target.addEventListener("load", event => { /* handle event */ });Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| onload | JavaScript handler body | Optional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute. |
| event | Event | Event object delivered to the addEventListener callback; event.type is "load". Inspect target, currentTarget, bubbles and cancelable as appropriate. |
Working Example
Example Snippethtml
<img id="demo" alt="Sample image"><p role="status" id="log">Waiting for load</p><script> const target = document.getElementById("demo"); const log = document.getElementById("log"); target.addEventListener("load", event => { log.textContent = String(event.type); }); target.src = "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2232%22%20height%3D%2232%22%3E%3Crect%20width%3D%2232%22%20height%3D%2232%22%20fill%3D%22teal%22%2F%3E%3C%2Fsvg%3E";</script>