Open In App

How to create a JavaScript callback for knowing if an image is loaded ?

Last Updated : 30 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The task is to know if an image is loaded using a JavaScript callback method. Please refer to JavaScript callbacks.

Method 1: By using .complete property.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Create a JavaScript callback for
        knowing if an image is loaded
    </title>
  
    <style>
        #sologo {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
  
<body>
  
    <img src=
        alt="Loading Image" id="sologo" />
  
    <script type="text/javascript">
        let img = document.querySelector('img')
  
        function loaded() {
            alert('loaded')
        }
  
        if (img.complete) {
            loaded()
        } else {
            img.addEventListener('load', loaded)
            img.addEventListener('error', function () {
                alert('error')
            })
        }
    </script>
</body>
  
</html>



Output:

Note:This program will continuously check if the image is loaded using the .complete property of the img element. It will also check for errors. When the image is loaded it will alert with “loaded” alert message box.

Method 2: Using image.onload() method

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Create a JavaScript callback for
        knowing if an image is loaded
    </title>
  
    <style>
        #sologo {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
  
<body>
    <img src="#" alt="Loading Image" id="sologo" />
  
    <script type="text/javascript">
        window.onload = function () {
  
            let logo = document.getElementById('sologo');
  
            logo.onload = function () {
                alert("loaded");
            };
  
            setTimeout(function () {
                logo.src = 
            }, 5000);
        };
    </script>
</body>
  
</html>



Output:

Note: In this method, Image.onload() is continuously checking if the image is loaded or not. If the image does not load within 5 seconds, it will timeout and show you an error. If the image is loaded after some set time, it alerts message saying “The image has loaded”.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads