Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Execute a script when an error occurs in HTML?
The onerror event in HTML allows you to execute a script when an error occurs while loading external resources like images, scripts, or stylesheets. This event is essential for handling loading failures gracefully and providing user feedback when resources cannot be accessed.
The onerror event is triggered when an external file fails to load, such as when an image source is broken, a script file is missing, or a stylesheet cannot be found. This event helps improve user experience by allowing developers to display alternative content or error messages.
Syntax
Following is the syntax for using the onerror attribute −
<element onerror="functionName()">
Following is the syntax for using the addEventListener() method with error events −
element.addEventListener("error", functionName);
Using the onerror Attribute
The onerror attribute can be added directly to HTML elements that load external resources. When the resource fails to load, the specified JavaScript function executes automatically.
Example − Image Loading Error
Following example demonstrates how to handle image loading errors using the onerror attribute −
<!DOCTYPE html>
<html>
<head>
<title>Image Error Handling</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Image Loading Test</h2>
<img src="nonexistent-image.jpg" onerror="handleImageError()" alt="Test Image" style="border: 1px solid #ccc;">
<p id="errorMessage"></p>
<script>
function handleImageError() {
document.getElementById("errorMessage").innerHTML = "?? Image could not be loaded. Please check the file path.";
document.getElementById("errorMessage").style.color = "red";
document.getElementById("errorMessage").style.fontWeight = "bold";
}
</script>
</body>
</html>
When the image fails to load, the onerror event triggers and displays an error message −
Image Loading Test [Broken image icon] ?? Image could not be loaded. Please check the file path.
Example − Script Loading Error
Following example shows how to handle script loading errors −
<!DOCTYPE html>
<html>
<head>
<title>Script Error Handling</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>External Script Loading</h2>
<p id="status">Loading external script...</p>
<script src="missing-script.js" onerror="handleScriptError()"></script>
<script>
function handleScriptError() {
document.getElementById("status").innerHTML = "? External script failed to load. Using fallback functionality.";
document.getElementById("status").style.color = "orange";
// Provide fallback functionality
console.log("Fallback: Script loaded locally");
}
</script>
</body>
</html>
When the external script fails to load, the error handler provides feedback and can implement fallback functionality.
Using addEventListener() Method
The addEventListener() method provides a more flexible way to handle error events. It allows you to attach multiple error handlers and provides better control over event handling.
Example − Multiple Image Error Handling
Following example demonstrates using addEventListener() to handle errors for multiple images −
<!DOCTYPE html>
<html>
<head>
<title>Multiple Image Error Handling</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Image Gallery with Error Handling</h2>
<div>
<img id="img1" src="image1.jpg" alt="Image 1" style="width: 150px; height: 100px; margin: 5px; border: 1px solid #ddd;">
<img id="img2" src="image2.jpg" alt="Image 2" style="width: 150px; height: 100px; margin: 5px; border: 1px solid #ddd;">
<img id="img3" src="image3.jpg" alt="Image 3" style="width: 150px; height: 100px; margin: 5px; border: 1px solid #ddd;">
</div>
<p id="errorLog"></p>
<script>
// Add error listeners to all images
const images = document.querySelectorAll('img');
let errorCount = 0;
images.forEach(function(img, index) {
img.addEventListener('error', function() {
errorCount++;
this.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMGYwIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPk5vIEltYWdlPC90ZXh0Pjwvc3ZnPg==';
this.alt = 'Image not found';
document.getElementById('errorLog').innerHTML =
`${errorCount} image(s) failed to load. Placeholder images displayed.`;
document.getElementById('errorLog').style.color = 'red';
});
});
</script>
</body>
</html>
This example adds error handling to multiple images and replaces failed images with placeholder graphics −
Image Gallery with Error Handling [No Image] [No Image] [No Image] 3 image(s) failed to load. Placeholder images displayed.
Example − Advanced Error Information
Following example shows how to capture detailed error information using event listeners −
<!DOCTYPE html>
<html>
<head>
<title>Detailed Error Information</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Resource Loading Monitor</h2>
<img id="testImage" src="broken-link.jpg" alt="Test Image">
<div id="errorDetails" style="margin-top: 20px; padding: 15px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px;"></div>
<script>
const img = document.getElementById('testImage');
const errorDetails = document.getElementById('errorDetails');
img.addEventListener('error', function(event) {
const timestamp = new Date().toLocaleTimeString();
const details = `
<h4 style="color: #856404; margin: 0 0 10px 0;">Error Details:</h4>
<p><strong>Time:</strong> ${timestamp}</p>
<p><strong>Element:</strong> ${this.tagName}</p>
<p><strong>Source:</strong> ${this.src}</p>
<p><strong>Alt Text:</strong> ${this.alt}</p>
<p><strong>Event Type:</strong> ${event.type}</p>
`;
errorDetails.innerHTML = details;
});
img.addEventListener('load', function() {
errorDetails.innerHTML = '<p style="color: green;">? Image loaded successfully!</p>';
});
</script>
</body>
</html>
This provides comprehensive error information including timestamp, element details, and event type when resources fail to load.
Common Use Cases
Error event handling is commonly used in the following scenarios −
Image galleries − Replace broken images with placeholder graphics or "image not found" messages.
External scripts − Provide fallback functionality when CDN resources fail to load.
Stylesheets − Load alternative CSS files or apply inline styles when external stylesheets fail.
User feedback − Inform users when content cannot be loaded and suggest alternatives.
Error logging − Track resource loading failures for debugging and monitoring purposes.
Comparison of Error Handling Methods
| Method | Usage | Advantages | Disadvantages |
|---|---|---|---|
| onerror attribute | Direct HTML attribute | Simple syntax, inline definition | Limited to one handler per element |
| addEventListener() | JavaScript method | Multiple handlers, better control, event object access | Requires JavaScript knowledge, more code |
| element.onerror | JavaScript property | Programmatic assignment | Overwrites existing handlers |
Conclusion
The onerror event is essential for robust web
