How to check whether the background image is loaded or not using JavaScript ?
In JavaScript, onload event is used to check whether a window is loaded or not. Similarly, we can use that event to check whether a particular element has loaded or not. There are two ways in which we can check whether a background image has loaded or not.
Syntax:
-
Using HTML:
<element onload="myScript">
-
Using onload attribute in JavaScript:
object.onload = function(){myScript}; -
Using addEventListener() method in JavaScript
object.addEventListener("load", myScript);
HTML approach:
HTML
<!DOCTYPE html> <html> <head> <script src= </script> <style> #bg_img { width: 50vw; height: 50vh; } </style> </head> <body> <h2>Welcome To GFG</h2> <p> Default code has been loaded into the Editor. </p> <img id="bg_img" onload="loadImage()" /> <p id="img_status"></p> <script> function loadImage() { document.getElementById("img_status") .innerHTML = "image loaded"; } document.getElementById("bg_img").src = let ele = document.getElementById("bg_img"); </script> </body> </html> |
chevron_right
filter_none
Output:

Using onload attribute:
HTML
<!DOCTYPE html> <html> <head> <script src= </script> <style> #bg_img { width: 50vw; height: 50vh; } </style> </head> <body> <h2>Welcome To GFG</h2> <p> Default code has been loaded into the Editor. </p> <img id="bg_img" /> <p id="img_status"></p> <script> let ele = document.getElementById("bg_img"); ele.onload = (e) => { document.getElementById("img_status") .innerHTML = "image loaded"; }; ele.src = </script> </body> </html> |
chevron_right
filter_none
Output:

Using addEventListener() method:
HTML
<!DOCTYPE html> <html> <head> <style> #bg_img { width: 50vw; height: 50vh; } </style> </head> <body> <h2>Welcome To GFG</h2> <p> Default code has been loaded into the editor </p> <img id="bg_img" /> <p id="img_status"></p> <script src= </script> <script> let ele = document.getElementById("bg_img"); ele.addEventListener("load", (e) => { document.getElementById("img_status") .innerHTML = "image loaded"; }); ele.src = </script> </body> </html> |
chevron_right
filter_none
Output:

Note: To use jQuery replace event listener code with the following –
$("#bg_img").on("load", function () {
window.alert("Image has loaded", 1);
});


