How to check whether the background image is loaded or not using JavaScript ?
Last Updated :
16 Jan, 2023
In this article, we will 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.
We can do this in three ways:
Using HTML:
Syntax:
<element onload="myScript">
Example: This example checks whether the background image is loaded or not using Html.
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 >
|
Output:
Using onload attribute in JavaScript:
Syntax:
object.onload = function(){myScript};
Example: This example checks whether the background image is loaded or not using onload attribute in Javascript.
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 >
|
Output:
Using addEventListener() method in JavaScript
Syntax:
object.addEventListener("load", myScript);
Example: This example checks whether the background image is loaded or not using the addEventListener() method in Javascript.
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 >
|
Output:
Note: To use jQuery replace the event listener code with the following –
$("#bg_img").on("load", function () {
window.alert("Image has loaded", 1);
});
Share your thoughts in the comments
Please Login to comment...