View video tutorial

HTML onerror Attribute

HTML

The HTML onerror attribute is an event handler that triggers the execution of a script when an error occurs while loading an external resource

Definition and Usage


➔ It is typically used to handle broken links to images, scripts, or media files.

➔ The primary purpose is to provide a nice fallback or log errors when a resource fails to load, which improves the user experience.

➔ The window.onerror event handler can capture common, elusive JavaScript runtime errors throughout the page and provides error messages and the reason for the failure.

Example
<img src="notexist.jpg" onerror="this.onerror=null; this.src='fallback.jpg';">
<!-- This line shows a common practice that prevents 
infinite loops even if the fallback image is not loaded. -->

Applies to

This attribute can be used on the following element.

Attribute Element
onerror <audio>, <body>, <embed>, <img>, <object>, <script>, <style>, <video>