Skip to content
Related Articles

Related Articles

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.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right



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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right



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

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :