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.

Syntax

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.

Example

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>
<html>
   <head>
      <title>detecting image load</title>
   </head>
   <body>
      <h1>case1</h1>
      <img src= "https://www.tutorialspoint.com/images/logo.png"
         onload="javascript: alert('image loaded')"
         onerror="javascript: alert('image failed to load')" />
      <h2>case2</h2>
      <img src="#" onload="javascript: alert('Image Loaded')"
         onerror="javascript: alert('Failed to load the image')" />
   </body>
</html>

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.

Example

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>
<html>
   <head>
      <title>detecting imagr load</title>
   </head>
   <body>
      <img src=
      "https://www.tutorialspoint.com/java/images/java-mini-logo.jpg">
      <script>
         window.addEventListener("load", event => {
            var image = document.querySelector('img');
            var load = image.complete;
            alert(load);
         });
      </script>
   </body>
</html>

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

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements