onerror

The onerror event is triggered when an error occurs while loading an external file, such as a document or image.

onerror event

The onerror event handler executes a specified script when an error occurs while loading an element, like an image or script. This is helpful for handling errors smoothly in web applications.

Syntax

In HTML

index.html
<element onerror="myScript">

In JS

script.js
object.onerror = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("error", myScript);

Example

::event-onerror ::
index.html
<!DOCTYPE html>
<html>
<body>
<img src="image.gif" onerror="myFunction()">
<p>A function is triggered if an error occurs when loading the image. The function shows an alert box with a text.
In this example we refer to an image that does not exist, therefore the onerror event occurs.</p>

<script>
function myFunction() {
  alert('The image could not be loaded.');
}
</script>

</body>
</html>

Values

Conclusion

The onerror event is essential for managing errors that occur during the loading of elements like <img> or <script> in web applications. It allows developers to implement fallback actions, ensuring that the user experience remains seamless even when resources fail to load.