Explain Codes LogoExplain Codes Logo

How to load images dynamically (or lazily) when users scroll them into view

web-development
lazy-loading
responsive-design
performance
Nikita BarsukovbyNikita Barsukov·Jan 2, 2025
TLDR

Use lazy loading - a neat little trick where we delay image loading until they're really needed. Simply add loading="lazy" in your <img> tags:

<img src="your-image.jpg" loading="lazy" alt="description">

If you need a catch-all approach due to browser compatibility issues, bring in the Intersection Observer API. It keeps an eye on the image elements and loads them when they become visible:

let observer = new Intersection Observer((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { // Must be the user's lucky day! let img = entry.target; img.src = img.dataset.src; observer.unobserve(img); } }); }); document.querySelectorAll('img[lazy]').forEach(img => observer.observe(img));

Replace source URLs with a data-src in your HTML, also use a placeholder attribute lazy:

<img data-src="your-image.jpg" alt="description" lazy>

It's JavaScript to the rescue again - managing the loading and switching data-src with src when needed.

Optimize images for quicker loading

Before turning a lazy programmer, remember to optimize your images. Use tools to squeeze 'em down and convert to a modern format like WebP for that extra speed boost:

<img data-src="your-image.webp" alt="description" lazy>

Best bet is to use responsive images with srcset and sizes, so devices get images specifically tailored to them:

<img data-srcset="your-image-300w.jpg 300w, your-image-600w.jpg 600w" sizes="(max-width: 600px) 300px, 600px" data-src="your-image-600w.jpg" alt="description" lazy>

Placeholders: essential for smooth scrolling

Don't leave users hanging with awkward jumps. Use a placeholder, either a simple color or a low-quality preview:

img[lazy] { background: #ccc; // Minimal but classy background: url('placeholder.jpg'); // A blurry sneak peek perhaps? }

Support for older browsers

Dealing with antiques? While modern browsers love lazy loading, older ones might need a Polyfill or a JavaScript-based fallback. Ready-made solutions are abundant or roll one yourself!

Lazy loading: The Arena of Plugins and Techniques

  • jQuery Lazyload: Perfect fit for jQuery projects.
  • Intersection Observer & Thresholds: Loading starts as images near the viewport. It's like laying out the welcome mat!
  • Dynamic & AJAX content: Add lazy functionality to dynamic content as it arrives, like gift-wrapping presents!

Mindful programming considerations

Don't forget: users might be in a network blackhole. Use service workers and cache APIs to store loaded images for offline use and quick re-display. It's neighbourhood friendly!

// Register a helpful service worker if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js'); // 'sw.js' is ready to serve...vicariously! }

Remember to consider accessibility. Ensure lazy loading doesn't trip screen readers and alt is always present for images.

Avoid loading all at once

Lots of unseen, unnecessary images? That's like a party where no one turns up. Calculate the chances of an image being seen based on user behavior to improve performance.