How to check whether an image is loaded or not ?

While inserting images in HTML pages sometimes the image may fail to load due to:
- Getting the image URL wrong
- poor internet connection
So we may want to check if the image is not loading due to these reasons. To check we can use the below methods
Method 1:Â
Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are:Â
- onload: The onload event is triggered when an image is loaded and is executed
- onerror: The onerror event is triggered if an error occurs during the execution
Example:Â
html
<!DOCTYPE html><html>Â Â <head>Â Â Â Â <title>Image load check</title>Â Â </head>Â Â <body>Â Â Â Â <img src=Â Â Â Â Â onload="javascript: alert('The image has been loaded')"Â Â Â Â Â onerror="javascript: alert('The image has failed to load')" />Â Â </body></html> |
Output:
when image is successfully loaded
when image loading fails
Method 2:Â
Using the image complete property in HTML DOM
This property returns a boolean value  if the image is loaded it returns true else it returns false
Example:Â
html
<!DOCTYPE html><html>Â Â <head>Â Â Â Â <title>Checking if image is loaded</title>Â Â </head>Â Â <script type="text/javascript">Â Â window.addEventListener("load", event => {Â Â var image = document.querySelector('img');Â Â var load = image.complete;Â Â alert(load);});Â Â </script>Â Â <body>Â Â Â Â <img src=Â Â </body></html> |
Here the variable load checks if the image is loaded or not. If an image is loaded then true is alerted else false is alerted.
Output:
when image is successfully loaded
when image load fails
Supported Browsers:
- Google Chrome
- Firefox
- Internet Explorer
- Safari
- Opera



