Explain Codes LogoExplain Codes Logo

Checking image load status with jQuery

javascript
image-load-status
jquery
event-handling
Anton ShumikhinbyAnton Shumikhin·Aug 27, 2024
TLDR

Leverage jQuery's .on() method to inspect an image's load status:

$('img.selector').on('load', function() { // Hosanna! Image has graced us with its presence. }).on('error', function() { // Sigh... seems like the image went AWOL. });

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.

function isImageOk(imgElement) { // Returns true if Santa (img element) has emptied his sack (image load is complete and successful). return imgElement.complete && imgElement.naturalHeight !== 0; }

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:

var testImage = new Image(); testImage.onerror = function() { // Oops... look who dropped their marbles during loading. }; testImage.onload = function() { // Finally... the image grew up and loaded itself. }; testImage.src = 'path/to/image.jpg';

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:

$(document).on('load', 'img.dynamic', function() { // Dynamically added images have successfully loaded, party time! }).on('error', 'img.dynamic', function() { // Even dynamism couldn't save the image from failing to load. });