The HTML onerror event
The HTML onerror attribute runs JavaScript when a resource fails to load, or a script error occurs. It is an inline handler for the error event; in modern code prefer addEventListener('error', …).
Overview
The onerror event attribute runs JavaScript when a resource fails to load. In JavaScript the event itself is named error — 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 onerror HTML attribute, but the modern, recommended approach is element.addEventListener('error', 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 onerror="handler()">…</element>
element.addEventListener('error', handler);
Example
<img src="does-not-exist.png" onerror="this.insertAdjacentText('afterend', ' Image failed to load.')" alt="" width="1" height="1">
Best practices
- Prefer
element.addEventListener('error', handler)over the inlineonerrorattribute — 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 onerror event?
error.When does this event fire?
How do I handle an image that fails to load?
Should I use the onerror attribute or addEventListener?
addEventListener('error', …) in JavaScript. The inline onerror attribute works but mixes behavior into the markup and allows only one handler per element.