How to Detect if An 'IMG' Element Load Has Started And/or a Request Has Been Made to the Server?

Sometimes when inserting images into HTML sites, the image may not load for the following reasons −

  • Because of image URL wrong

  • Network issues

The task we are going to perform was detecting if an img element load has started and/or request has made to the server. Before this let’s have a quick view on the HTML <img>tag.

HTML <img> tag

To insert an image into a webpage, use the HTML tag. In modern websites, images are linked to web pages using the <img> element, which contains space for the image. This prevents websites from directly adding images to web pages.


Following is the syntax for <img> tag

<img src="" alt="" width="" height="">

Let’s look into the following example for getting better understanding on detecting if an image has loaded and/or request has made to the server.


In the following example, we are creating a simple form for checking if the image is loaded or a request has been made to the server.

<!DOCTYPE html>
      <title>detecting image load</title>
      <img src= ""
         onload="javascript: alert('image loaded')"
         onerror="javascript: alert('image failed to load')" />
      <img src="#" onload="javascript: alert('Image Loaded')"
         onerror="javascript: alert('Failed to load the image')" />

When the script gets executed, it will generate an output displaying an alert showing an image loaded and displaying an image on the webpage. In the second case, it will display an alert showing an image failed to load and display the default broken image.


Consider the following example, we are using the image-complete property in HTML, which returns a Boolean value: If the image is loaded, it displays true; otherwise, it displays false.

<!DOCTYPE html>
      <title>detecting imagr load</title>
      <img src=
         window.addEventListener("load", event => {
            var image = document.querySelector('img');
            var load = image.complete;

On running the above script, the output window will pop up showing alert "true" and displaying an image on the webpage.

Updated on: 20-Apr-2023


Kickstart Your Career

Get certified by completing the course

Get Started