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 weather an image is loaded or not. The attributes we will use are:

  • onload: The onload event is triggered when a image is loaded and is executed
  • onerror: The onerror event is triggered if an error occurs during the execution

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


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:


Supported Browsers:

  • Google Chrome
  • Firefox
  • Interent Explorer
  • Safari
  • Opera

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.