Explain Codes LogoExplain Codes Logo

Preloading images with jQuery

javascript
image-preloading
error-handling
ajax-callbacks
Alex KataevbyAlex Kataev·Aug 12, 2024
TLDR

To effectively preload images utilizing jQuery, initiate a $.each() loop that goes over your image URLs. For every URL, instantiate a new Image() and assign its src. This nudges the browser to cache them instantly:

['img1.jpg', 'img2.png'].forEach(src => { $('<img>').attr('src', src).appendTo('body').hide(); });

This useful snippet acts as a double-duty worker, preloading your images and also ensuring that they are available promptly as and when required.

The image preloading rollercoaster: Onload and onerror

When working with a hefty batch of images, consider attaching onload and onerror events to track progress and handle unforeseen loading issues:

function preloadImages(sources, callback) { var counter = 0; // Start the counter at zero, just like replaying a sad song sources.forEach(src => { var img = new Image(); // Create a new image. It's empty, like my coffee cup. img.onload = () => { counter++; // One more image to the party if(counter === sources.length) { callback(); // Time to invite the guests, all images loaded! } }; img.onerror = () => { console.error(`Image failed to load: ${src}`); // Oops! Someone tripped on the way }; img.src = src; // Here's the map for the party! }); }

A failure to load can risk your user interface. Robust handling has you covered!

Got a minute? Try shorthand!

For instances where rapid prototyping or lower image quantities are in play, $(new Image()).src = 'image-url.jpg'; can be a more concise and speedy approach.

It's about time!

Load times play a key role in the overall user experience. Be strategic about when to preload; post main content load or during user downtime are optimal moments. Utilize Ajax callbacks to trigger preloading for images needed later; this shields the user from lags and keeps your pages looking sharp and professional.

No fluff, just stuff!

While jQuery plugins bring a world of functionalities on the table, do you really need it all? Evaluate your needs against the overhead of dependencies. More often than not, basic JavaScript coupled with jQuery's clean syntax will get the job done.

Watch the game: Preloading progress

In instances with heavy visuals or progressive web apps (PWAs), you may choose to use a progress bar for superior UX. Use img.onload and img.onerror to provide users a peek into the behind-the-scenes:

// 'progress-update' is a hypothetical function updating the UI sources.forEach(src => { var img = new Image(); img.onload = () => { counter++; progressUpdate(counter, sources.length); // Progress bar, loading edition! }; img.src = src; });

In case of hiccups: Error handling

Errors are a part of the game. Broken paths or network interruptions can be annoying. Arm yourself with robust error handling mechanisms:

img.onerror = () => { // Error handling: Because precaution is better than cure! handleImageLoadError(src); };

Look before you load: Conditional loading

Why load what you can't see? Load smart - only when it's visible or soon will be. Media queries or jQuery .in-viewport plugin can come in handy:

if($('#myImage').is(':in-viewport')) { preloadImages(['img-visible-on-viewport.jpg']); }