Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

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

  • Last Updated : 30 Jun, 2020

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.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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”.




My Personal Notes arrow_drop_up
Recommended Articles
Page :