Checking image load status with jQuery
Leverage jQuery's .on()
method to inspect an image's load status:
This snippet responds when the image is loaded lucratively or disappointingly fails.
Cross-verifying image load with natural
properties and img.complete
The img.complete
property comes in handy if you want to examine the load status of the image after the page has loaded. Although, img.complete
might not be reliable every time, as it yields true
even for a broken image, creating a tricky situation.
To resolve this, inspect the naturalWidth
and naturalHeight
properties concurrently, as these properties return non-zero values only if the image has loaded successfully.
If this function emits a true
, rest assured, your image load status check is fruitful.
Handling the unexpected: Pre-event registration errors
Juggling errors that visit before the jQuery event binding can be efficiently done by wielding the onerror
event along with an in-memory image:
This method invites error detection at the earliest possible moment.
Shifting Gears: The imagesLoaded
library
For those who have a norm to use a dedicated library to manage image load events, you can count on imagesLoaded
. It objectively checks for image loading and errors, and employs a browser support which can be termed as robust. Feel free to use this library as a jQuery plugin or even with plain JavaScript. For a closer look, explore its documentation.
Exercising jQuery for dynamically added images
While maintaining dynamically added images, conventional event bindings might disappoint you. Delegate events with the .on()
method by connecting the event to an existing parent element:
Was this article helpful?