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


HTML



Edit in JSFiddle

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



Edit in JSFiddle

 
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:

That’s all about determining whether an image is loaded with JavaScript.