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
How to check whether image is loaded or not?
To check whether an image is loaded in JavaScript, you can use event listeners or the complete property. This is useful for handling loading states, showing fallbacks, or performing actions after images load.
Common Image Loading Issues
Images may fail to load due to:
- Large file size causing slow loading
- Poor network connectivity
- Incorrect image URL or path
- Server errors or missing files
Available Methods
onload event ? Triggers when the image loads successfully
onerror event ? Triggers when the image fails to load
complete property ? Boolean property that indicates if the image has finished loading
Method 1: Using Event Listeners
Use addEventListener to handle both successful loading and errors:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Check Image Loading with Events</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
}
img {
max-width: 300px;
border: 2px solid #ddd;
border-radius: 8px;
margin: 20px;
}
.status {
padding: 10px;
margin: 10px;
border-radius: 4px;
}
.success { background-color: #d4edda; color: #155724; }
.error { background-color: #f8d7da; color: #721c24; }
</style>
</head>
<body>
<h2>Image Loading Status</h2>
<img src="https://www.tutorialspoint.com/images/logo.png" id="testImage" alt="TutorialsPoint Logo">
<div id="status">Loading...</div>
<script>
const img = document.getElementById('testImage');
const status = document.getElementById('status');
img.addEventListener('load', function() {
status.innerHTML = '<div class="status success">? Image loaded successfully!</div>';
console.log('Image dimensions:', img.naturalWidth + 'x' + img.naturalHeight);
});
img.addEventListener('error', function() {
status.innerHTML = '<div class="status error">? Failed to load image</div>';
console.log('Image failed to load');
});
</script>
</body>
</html>
? Image loaded successfully!
Method 2: Using the complete Property
The complete property returns true if the image has finished loading (successfully or with error):
<!DOCTYPE html>
<html lang="en">
<head>
<title>Check Image Loading with complete Property</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
}
img {
max-width: 300px;
border: 2px solid #ddd;
border-radius: 8px;
margin: 20px;
}
button {
padding: 10px 20px;
margin: 10px;
border: none;
border-radius: 4px;
background-color: #007bff;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Check Image Status</h2>
<img src="https://www.tutorialspoint.com/images/logo.png" id="checkImage" alt="TutorialsPoint Logo">
<br>
<button onclick="checkImageStatus()">Check Image Status</button>
<div id="result"></div>
<script>
function checkImageStatus() {
const img = document.getElementById('checkImage');
const result = document.getElementById('result');
if (img.complete) {
if (img.naturalWidth === 0) {
result.innerHTML = '<p style="color: red;">Image failed to load</p>';
} else {
result.innerHTML = '<p style="color: green;">Image loaded successfully!<br>Size: ' +
img.naturalWidth + 'x' + img.naturalHeight + '</p>';
}
} else {
result.innerHTML = '<p style="color: orange;">Image is still loading...</p>';
}
}
// Check immediately when page loads
window.addEventListener('load', checkImageStatus);
</script>
</body>
</html>
Image loaded successfully! Size: 140x55
Method 3: Dynamic Image Loading
Create and load images dynamically with Promise-based approach:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dynamic Image Loading</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
text-align: center;
}
.image-container {
margin: 20px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
}
button {
padding: 10px 20px;
margin: 10px;
border: none;
border-radius: 4px;
background-color: #28a745;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Dynamic Image Loading</h2>
<button onclick="loadImage('https://www.tutorialspoint.com/images/logo.png')">Load Valid Image</button>
<button onclick="loadImage('invalid-url.jpg')">Load Invalid Image</button>
<div id="imageContainer" class="image-container">
<p>Click a button to load an image</p>
</div>
<script>
function loadImagePromise(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error('Failed to load image'));
img.src = src;
});
}
async function loadImage(src) {
const container = document.getElementById('imageContainer');
container.innerHTML = '<p>Loading image...</p>';
try {
const img = await loadImagePromise(src);
container.innerHTML = `
<p style="color: green;">? Image loaded successfully!</p>
<p>Dimensions: ${img.width}x${img.height}</p>
`;
container.appendChild(img);
} catch (error) {
container.innerHTML = `
<p style="color: red;">? ${error.message}</p>
<p>URL: ${src}</p>
`;
}
}
</script>
</body>
</html>
Comparison of Methods
| Method | Use Case | Advantages | Limitations |
|---|---|---|---|
| Event Listeners | Real-time monitoring | Immediate response to load/error | Must be set before loading |
| complete Property | Check current status | Can check anytime | Doesn't distinguish success/error |
| Promise-based | Dynamic loading | Modern async/await syntax | More complex implementation |
Key Points
- Always handle both success and error cases
- Use
naturalWidthproperty to distinguish between successful load and error when usingcomplete - Event listeners must be attached before the image starts loading
- Consider using loading indicators for better user experience
Conclusion
JavaScript provides multiple ways to check image loading status. Use event listeners for real-time monitoring, the complete property for status checks, or Promise-based approaches for modern dynamic loading with proper error handling.
