Check whether an image is loaded with JavaScript/jQuery
This post will discuss how to check whether an image is loaded with JavaScript. Checking whether an image is loaded means determining whether the image has been completely downloaded and rendered by the browser.
1. Using complete attribute
To determine whether an image has been completely loaded, we can use the complete attribute of the HTMLImageElement interface. This attribute is a boolean property that returns true if the image has been completely loaded, and false otherwise. We should use this with naturalWidth or naturalHeight properties, which are also part of the HTMLImageElement interface. These properties return the intrinsic width and height of the image in pixels, respectively. These properties would return 0 when the image failed to load. So if either of the values are greater than 0, it means that the image has been completely loaded.
JS
|
1 2 3 4 5 |
window.addEventListener("load", event => { var image = document.querySelector('img'); var isLoaded = image.complete && image.naturalHeight !== 0; alert(isLoaded); }); |
HTML
|
1 |
<img src="https://secure.gravatar.com/avatar?d=wavatar"/> |
2. Using onload and onerror events
Another way to check whether an image is loaded with JavaScript is to use the onload and onerror events. These events are built-in functions that are triggered when an image is successfully loaded or fails to load, respectively. The onload event is a success event that indicates that the image has been completely downloaded and rendered by the browser. The onerror event is an error event that indicates that the image has failed to load due to some reason, such as a broken link, a network error, or a cross-origin issue.
HTML
|
1 2 3 |
<img src="https://secure.gravatar.com/avatar?d=wavatar" onload="javascript: alert('success')" onerror="javascript: alert('failure')" /> |
To check whether an image is loaded with jQuery, we can attach the load and error events to any image element using the jQuery selector and the on() function. For example, if we have an image element with an id of "profile_pic", we can use the following code:
|
1 2 3 4 5 6 |
// Select the image element by id $("#profile_pic").on("load", function() { console.log("Image is loaded!"); }).on("error", function() { console.log("Image is not loaded!"); }); |
That’s all about determining whether an image is loaded with JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)