👀 Live Preview
The image below uses a broken URL — error swaps in a fallback:

Waiting for error handler…

The onerror attribute is an inline event handler that runs JavaScript when the error event fires. That happens when an external resource fails to load — a broken image URL, a missing script file, or a media file the browser cannot decode. The most common beginner pattern is an <img> that swaps to a fallback image. Use onerror to keep pages usable when assets fail, log failures, or show placeholder content. It is not the same as onabort (load canceled) or window.onerror (uncaught JavaScript exceptions).
Inline JS.
Load failed.
Swap src.
Other targets.
Preferred way.
Fail vs cancel.
onerror AttributeThe primary purpose of onerror is to recover gracefully when resources fail. A product photo might 404 — show a placeholder instead of a broken icon. A CDN script might be blocked — load a local backup or disable a feature safely. Media that cannot decode fires error on audio or video.
Always guard against infinite loops: if the fallback image also fails, clear onerror or check that you have not already swapped the source before assigning a new src.
Production apps often use img.addEventListener("error", handler). Inline onerror="this.src='fallback.png'" is a valid quick pattern for simple fallbacks.
Set onerror on an element that loads external content:
<img src="photo.jpg" alt="Product" onerror="handleImageError(this)">
<script>
function handleImageError(img) {
img.onerror = null;
img.src = "/images/placeholder.png";
}
</script>error event fires.<img>, <script src>, <audio>, <video>, <link>, <track>.onabort).element.onerror = function() { … }.element.addEventListener("error", handler).onerror after swapping src to avoid infinite error loops.The onerror attribute accepts a string of JavaScript code:
onerror="handleError()" — Call a named function.onerror="this.onerror=null;this.src='fallback.png'" — Inline one-liner fallback.img.onerror = () => { … } assigns the handler.const img = document.getElementById("avatar");
img.addEventListener("error", () => {
img.onerror = null;
img.src = "/images/default-avatar.png";
img.alt = "Default avatar";
});| Scenario | error fires? | Typical fix |
|---|---|---|
| 404 image URL | Yes | Swap to placeholder src |
Script src blocked | Yes | Load backup script or degrade feature |
| User cancels download | No | Use onabort |
| Successful load | No | Use onload |
| Uncaught JS exception | No | window.onerror (different API) |
| Handler attribute | onerror | Inline on resource element |
| Target | Supported? | Notes |
|---|---|---|
<img> | Yes | Most common — fallback images |
<script src> | Yes | External script load failure |
<audio>, <video> | Yes | Media decode or network error |
<link>, <track> | Yes | Stylesheet, caption file errors |
<div>, <button> | No | Not resource load events |
onerror vs onabort vs onload| Handler | When it fires | Typical cause |
|---|---|---|
onerror | Resource failed to load | Bad URL, network error, corrupt file |
onabort | Load stopped before completion | Script cleared src mid-load |
onload | Resource loaded successfully | Happy path |
Image fallback with inline onerror, addEventListener, and a compact one-liner pattern.
The image below uses a broken URL — error swaps in a fallback:

Waiting for error handler…
Log the failure and swap to a placeholder:
<script>
function handleImageError(img) {
console.log("Error loading image!");
img.onerror = null;
img.src = "fallback.jpg";
}
</script>
<img src="example.jpg" alt="Product photo" onerror="handleImageError(this)">Pass this from the inline handler so the function can update the same img element. Clearing onerror prevents a loop if the fallback also fails.
Attach the handler with addEventListener:
<script>
var img = document.getElementById("dynamicImage");
img.addEventListener("error", function () {
console.log("Dynamic image loading error!");
this.onerror = null;
this.src = "dynamic-fallback.jpg";
});
// Or property form:
img.onerror = function () { /* … */ };
</script>Register the listener once at page load. When the image request fails, your recovery logic runs before the user sees a broken icon.
A common one-liner for simple placeholder swaps:
<img
src="avatar.jpg"
alt="User avatar"
onerror="this.onerror=null;this.src='default-avatar.png';">Setting this.onerror = null inside the handler prevents infinite loops if the fallback URL also fails.
alt on fallback — If the placeholder conveys different meaning, change alt text in the error handler.alt="" when appropriate; still provide fallbacks for layout stability if needed.Image, script, or media request starts.
404, network, or decode error.
onerror handler runs.
Fallback asset or message.
The error event and onerror handler are supported in all modern browsers on resource-loading elements — Chrome, Firefox, Safari, and Edge.
onerror supportAll major browsers fire the underlying event and honor the onerror handler attribute.
Bottom line: Use onerror confidently for image and resource fallbacks; prefer addEventListener in production code.
element.onerror = null after swapping srcaddEventListener("error", …) in maintainable codealt text on imagesonerror with window.onerroralert() when a resource failsonerror when the user aborts a load (onabort)The onerror attribute runs JavaScript when a resource fails to load — essential for image placeholders, script recovery, and resilient media players.
Prefer addEventListener("error", …), clear handlers after fallback swaps, and distinguish error from abort and global JavaScript error reporting.
onerrorBookmark these before shipping user-facing images.
error fires.
EventSwap src.
PatternStop loops.
SafetyPreferred.
ModernFail vs cancel.
Compareerror event fires — when an external resource fails to load.img, script, audio, video, link, and track among others that fetch external resources.onerror means the load failed. onabort means loading was canceled before it finished.onerror stops that loop.addEventListener("error", handler) is preferred for production. Inline one-liners are fine for simple image fallbacks.onerror handles resource load failures. window.onerror catches uncaught JavaScript runtime errors.Practice the onerror attribute with image placeholder examples in the Try It editor.
5 people found this page helpful