HTML onerror Attribute

Beginner
⏱️ 5 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

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).

What You’ll Learn

01

Event handler

Inline JS.

02

error event

Load failed.

03

img fallback

Swap src.

04

script / media

Other targets.

05

addEventListener

Preferred way.

06

vs onabort

Fail vs cancel.

Purpose of onerror Attribute

The 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.

💡
Prefer addEventListener for maintainable code

Production apps often use img.addEventListener("error", handler). Inline onerror="this.src='fallback.png'" is a valid quick pattern for simple fallbacks.

📝 Syntax

Set onerror on an element that loads external content:

onerror.html
<img src="photo.jpg" alt="Product" onerror="handleImageError(this)">

<script>
  function handleImageError(img) {
    img.onerror = null;
    img.src = "/images/placeholder.png";
  }
</script>

Syntax Rules

  • Value is JavaScript executed when the error event fires.
  • Common on <img>, <script src>, <audio>, <video>, <link>, <track>.
  • Fires on load failure — not when loading is intentionally aborted (onabort).
  • JavaScript: element.onerror = function() { … }.
  • Modern alternative: element.addEventListener("error", handler).
  • Clear onerror after swapping src to avoid infinite error loops.

💎 Values

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.
  • JavaScript: img.onerror = () => { … } assigns the handler.
onerror-js.html
const img = document.getElementById("avatar");

img.addEventListener("error", () => {
  img.onerror = null;
  img.src = "/images/default-avatar.png";
  img.alt = "Default avatar";
});

⚡ Quick Reference

Scenarioerror fires?Typical fix
404 image URLYesSwap to placeholder src
Script src blockedYesLoad backup script or degrade feature
User cancels downloadNoUse onabort
Successful loadNoUse onload
Uncaught JS exceptionNowindow.onerror (different API)
Handler attributeonerrorInline on resource element

Applicable Elements

TargetSupported?Notes
<img>YesMost common — fallback images
<script src>YesExternal script load failure
<audio>, <video>YesMedia decode or network error
<link>, <track>YesStylesheet, caption file errors
<div>, <button>NoNot resource load events

onerror vs onabort vs onload

HandlerWhen it firesTypical cause
onerrorResource failed to loadBad URL, network error, corrupt file
onabortLoad stopped before completionScript cleared src mid-load
onloadResource loaded successfullyHappy path

Examples Gallery

Image fallback with inline onerror, addEventListener, and a compact one-liner pattern.

👀 Live Preview

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

Demo product photo

Waiting for error handler…

Example — Image fallback with handleImageError

Log the failure and swap to a placeholder:

inline-onerror.html
<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)">
Try It Yourself

How It Works

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.

Dynamic Values with JavaScript

Attach the handler with addEventListener:

dynamic-onerror.html
<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>
Try It Yourself

How It Works

Register the listener once at page load. When the image request fails, your recovery logic runs before the user sees a broken icon.

Example — Compact inline fallback

A common one-liner for simple placeholder swaps:

onerror-oneliner.html
<img
  src="avatar.jpg"
  alt="User avatar"
  onerror="this.onerror=null;this.src='default-avatar.png';">
Try It Yourself

How It Works

Setting this.onerror = null inside the handler prevents infinite loops if the fallback URL also fails.

♿ Accessibility

  • Update alt on fallback — If the placeholder conveys different meaning, change alt text in the error handler.
  • Do not rely on broken icons — Users with slow networks deserve a visible fallback, not an empty box.
  • Avoid alert() on error — Log silently or show non-blocking UI instead.
  • Decorative images — Use alt="" when appropriate; still provide fallbacks for layout stability if needed.
  • Announce critical failures — For essential content, use a live region if the fallback is text-only.

🧠 How onerror Works

1

Browser fetches resource

Image, script, or media request starts.

Request
2

Load fails

404, network, or decode error.

Failure
3

error fires

onerror handler runs.

Event
=

Graceful recovery

Fallback asset or message.

Browser Support

The error event and onerror handler are supported in all modern browsers on resource-loading elements — Chrome, Firefox, Safari, and Edge.

DOM Events · Fully supported

Universal onerror support

All major browsers fire the underlying event and honor the onerror handler attribute.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onerror attribute 99% supported

Bottom line: Use onerror confidently for image and resource fallbacks; prefer addEventListener in production code.

💡 Best Practices

✅ Do

  • Provide fallback images for user-uploaded or CDN URLs
  • Set element.onerror = null after swapping src
  • Use addEventListener("error", …) in maintainable code
  • Keep meaningful alt text on images
  • Log failures for debugging without blocking the UI

❌ Don’t

  • Confuse resource onerror with window.onerror
  • Trigger infinite error loops with a bad fallback URL
  • Use alert() when a resource fails
  • Expect onerror when the user aborts a load (onabort)
  • Hide all failure feedback from users on critical content

Conclusion

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.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onerror

Bookmark these before shipping user-facing images.

5
Core concepts
🖼️ 02

img fallback

Swap src.

Pattern
🔄 03

Null handler

Stop loops.

Safety
📝 04

addEventListener

Preferred.

Modern
05

Not abort

Fail vs cancel.

Compare

❓ Frequently Asked Questions

It runs JavaScript when the error 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.
If the fallback URL also fails, the handler would run again forever. Clearing onerror stops that loop.
addEventListener("error", handler) is preferred for production. Inline one-liners are fine for simple image fallbacks.
No. Element onerror handles resource load failures. window.onerror catches uncaught JavaScript runtime errors.

Build resilient pages with error fallbacks

Practice the onerror attribute with image placeholder examples in the Try It editor.

Try onerror demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful