Media Lazy Loading
Master media lazy loading strategies — native browser lazy loading for images and iframes, video poster optimization, low-quality image placeholders (LQIP), BlurHash encoding, progressive rendering techniques, and prioritization of above-the-fold media.
When to Use
- A page contains many images but only 2-3 are visible on initial load
- Lighthouse flags "Defer offscreen images" with significant byte savings
- Page load downloads all images regardless of whether they are in the viewport
- Video embeds (YouTube, Vimeo) load heavy iframes before the user clicks play
- Image-heavy galleries or product listings transfer megabytes on initial load
- Placeholder images cause layout shift when the real image loads
- Users perceive the page as slow because all media loads simultaneously
- A content-heavy blog or news site loads images for the entire article at once
- Infinite scroll feeds download images for items far below the current scroll position
- Third-party image embeds (Instagram, Twitter) add hundreds of KB to page weight
Instructions
Use native lazy loading for below-fold images. The loading="lazy" attribute defers image loading until the image approaches the viewport:
<!-- Below-fold images: lazy load -->
<img
src="product.jpg"
alt="Product photo"
width="400"
height="300"
loading="lazy"
decoding="async"
/>
<!-- Above-fold / LCP images: NEVER lazy load -->
<img src="hero.jpg" alt="Hero banner" width="1200" height="600" fetchpriority="high" />
The browser determines the loading threshold (typically 1250-2500px from viewport depending on connection speed). Do not add loading="lazy" to the LCP image or any image visible in the initial viewport.
Lazy load iframes for video embeds. YouTube and Vimeo iframes load 500KB+ of JavaScript. Defer until the user indicates intent:
<!-- Native iframe lazy loading -->
<iframe
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
loading="lazy"
width="560"
height="315"
title="Video title"
allow="accelerometer; autoplay; encrypted-media"
allowfullscreen
></iframe>
<!-- Better: facade pattern — show thumbnail, load iframe on click -->
function YouTubeFacade({ videoId, title }: { videoId: string; title: string }) {
const [loaded, setLoaded] = useState(false);
if (loaded) {
return (
<iframe
src={`https://www.youtube.com/embed/${videoId}?autoplay=1`}
width="560"
height="315"
title={title}
allow="accelerometer; autoplay; encrypted-media"
allowfullscreen
/>
);
}
return (
<button
=> setLoaded(true)}
style={{ position: 'relative', width: 560, height: 315 }}
aria-label={`Play: ${title}`}
>
<img
src={`https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`}
alt={title}
width="560"
height="315"
loading="lazy"
/>
<PlayIcon />
</button>
);
}
Implement LQIP (Low-Quality Image Placeholders). Show a tiny blurred preview while the full image loads:
// Generate LQIP at build time with sharp
const sharp = require('sharp');
async function generateLQIP(inputPath) {
const buffer = await sharp(inputPath)
.resize(20) // 20px wide
.blur(2)
.jpeg({ quality: 20 })
.toBuffer();
return `data:image/jpeg;base64,${buffer.toString('base64')}`;
// ~200-400 bytes, inlineable in HTML
}
<!-- LQIP placeholder with fade-in transition -->
<div class="image-container" style="aspect-ratio: 4/3;">
<img
src="data:image/jpeg;base64,/9j/4AAQSkZJ..."
data-src="product-full.jpg"
alt="Product"
class="lqip-image"
width="800"
height="600"
/>
</div>
<style>
.image-container {
overflow: hidden;
}
.lqip-image {
width: 100%;
height: 100%;
object-fit: cover;
filter: blur(20px);
transform: scale(1.1);
transition:
filter 0.3s,
transform 0.3s;
}
.lqip-image.loaded {
filter: blur(0);
transform: scale(1);
}
</style>
Use BlurHash for compact placeholders. BlurHash encodes a placeholder in ~20-30 characters, decoded to a blurred preview on the client:
// Server: encode at upload/build time using sharp + blurhash
import { encode } from 'blurhash';
import sharp from 'sharp';
async function generateBlurHash(imagePath: string): Promise<string> {
const { data, info } = await sharp(imagePath)
.raw()
.ensureAlpha()
.resize(32, 32, { fit: 'inside' })
.toBuffer({ resolveWithObject: true });
return encode(new Uint8ClampedArray(data), info.width, info.height, 4, 3);
}
// Client: decode hash to pixels, render to <canvas> via ctx.putImageData()
Implement video poster optimization. For video elements, use a poster image to avoid loading video data before play:
<video poster="video-poster.webp" preload="none" width="1280" height="720" playsinline>
<source src="video.mp4" type="video/mp4" />
</video>
Set preload="none" to prevent the browser from downloading any video data. The poster image provides the visual preview. Combine with loading="lazy" on a facade image for below-fold videos.
Implement progressive image loading with CSS transitions. Preload the full image in a new Image(), swap src on load, and animate with filter: blur(20px) transitioning to filter: none over 300ms. This smooths the placeholder-to-image transition without layout shift.
Configure the loading threshold. Browsers load lazy images before they enter the viewport. Chrome uses a distance threshold that varies by connection speed (~1250px on 4G, ~2500px on slow 3G). For custom Intersection Observer implementations, set rootMargin based on image size and expected scroll speed:
// Small thumbnails (fast to load): trigger closer
const observer = new IntersectionObserver(callback, { rootMargin: '200px' });
// Large hero images (slow to load): trigger earlier
const observer = new IntersectionObserver(callback, { rootMargin: '500px' });
Details
Native Lazy Loading Browser Behavior
When loading="lazy" is set, the browser defers the image fetch until the image is within a distance threshold of the viewport. This threshold is not configurable by developers — it varies by browser and connection speed. Chrome on a fast connection starts loading images ~1250px before they enter the viewport. On slow 3G, this increases to ~2500px to compensate for longer download times. Images with loading="lazy" that are in the initial viewport on page load are loaded immediately (no deferral).
Worked Example: Medium Article Images
Medium inlines a ~200-byte blurred LQIP as a base64 data URI. When the container approaches the viewport (Intersection Observer, 300px rootMargin), the full image loads and a CSS transition fades from blur to sharp over 300ms. Result: zero layout shift, immediate visual feedback, and ~95% of image bytes deferred.
Worked Example: Instagram Feed
Each API response includes a 28-character BlurHash string rendered to a canvas as an instant placeholder. The actual image loads progressively (headers first, then increasing resolution scans). Result: colored blurred previews within 50ms of scrolling, zero layout shift, and perceived-instant loading.
Anti-Patterns
Lazy loading the LCP image. Adding loading="lazy" to the hero image or any image visible without scrolling delays LCP by the intersection observer threshold plus download time. The LCP image should be eagerly loaded with fetchpriority="high".
Using JavaScript lazy loading when native suffices. Libraries like lazysizes add JavaScript overhead for functionality the browser provides natively. Use loading="lazy" for standard cases. Reserve JavaScript solutions for LQIP, BlurHash, or Intersection Observer patterns that native lazy loading cannot provide.
Placeholders that cause layout shift. A placeholder with different dimensions than the final image causes Cumulative Layout Shift when swapped. Always set width, height, and aspect-ratio on containers. Placeholders must match the final image's aspect ratio.
Lazy loading all images indiscriminately. Applying loading="lazy" to every image on the page, including above-the-fold images, delays rendering of critical content. Audit which images are in the initial viewport and exclude them from lazy loading.
Source
Process
- Read the instructions and examples in this document.
- Apply the patterns to your implementation, adapting to your specific context.
- Verify your implementation against the details and edge cases listed above.
Harness Integration
- Type: knowledge — this skill is a reference document, not a procedural workflow.
- No tools or state — consumed as context by other skills and agents.
Success Criteria
- Below-fold images use
loading="lazy" and above-fold images do not.
- Video embeds use a facade pattern that loads the iframe only on interaction.
- Image placeholders (LQIP or BlurHash) are implemented for key images.
- No media lazy loading causes layout shift (containers have explicit dimensions).
- Initial page load transfers only images visible in the viewport.
1---2name: perf-lazy-loading-media3description: Media Lazy Loading4metadata:5 source: https://skillmd.com/skills/intense-visions/perf-lazy-loading-media6---7# Media Lazy Loading89> Master media lazy loading strategies — native browser lazy loading for images and iframes, video poster optimization, low-quality image placeholders (LQIP), BlurHash encoding, progressive rendering techniques, and prioritization of above-the-fold media.1011## When to Use1213- A page contains many images but only 2-3 are visible on initial load14- Lighthouse flags "Defer offscreen images" with significant byte savings15- Page load downloads all images regardless of whether they are in the viewport16- Video embeds (YouTube, Vimeo) load heavy iframes before the user clicks play17- Image-heavy galleries or product listings transfer megabytes on initial load18- Placeholder images cause layout shift when the real image loads19- Users perceive the page as slow because all media loads simultaneously20- A content-heavy blog or news site loads images for the entire article at once21- Infinite scroll feeds download images for items far below the current scroll position22- Third-party image embeds (Instagram, Twitter) add hundreds of KB to page weight2324## Instructions25261. **Use native lazy loading for below-fold images.** The `loading="lazy"` attribute defers image loading until the image approaches the viewport:2728 ```html29 <!-- Below-fold images: lazy load -->30 <img31 src="product.jpg"32 alt="Product photo"33 width="400"34 height="300"35 loading="lazy"36 decoding="async"37 />3839 <!-- Above-fold / LCP images: NEVER lazy load -->40 <img src="hero.jpg" alt="Hero banner" width="1200" height="600" fetchpriority="high" />41 ```4243 The browser determines the loading threshold (typically 1250-2500px from viewport depending on connection speed). Do not add `loading="lazy"` to the LCP image or any image visible in the initial viewport.44452. **Lazy load iframes for video embeds.** YouTube and Vimeo iframes load 500KB+ of JavaScript. Defer until the user indicates intent:4647 ```html48 <!-- Native iframe lazy loading -->49 <iframe50 src="https://www.youtube.com/embed/dQw4w9WgXcQ"51 loading="lazy"52 width="560"53 height="315"54 title="Video title"55 allow="accelerometer; autoplay; encrypted-media"56 allowfullscreen57 ></iframe>5859 <!-- Better: facade pattern — show thumbnail, load iframe on click -->60 ```6162 ```typescript63 function YouTubeFacade({ videoId, title }: { videoId: string; title: string }) {64 const [loaded, setLoaded] = useState(false);6566 if (loaded) {67 return (68 <iframe69 src={`https://www.youtube.com/embed/${videoId}?autoplay=1`}70 width="560"71 height="315"72 title={title}73 allow="accelerometer; autoplay; encrypted-media"74 allowfullscreen75 />76 );77 }7879 return (80 <button81 onClick={() => setLoaded(true)}82 style={{ position: 'relative', width: 560, height: 315 }}83 aria-label={`Play: ${title}`}84 >85 <img86 src={`https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`}87 alt={title}88 width="560"89 height="315"90 loading="lazy"91 />92 <PlayIcon />93 </button>94 );95 }96 ```97983. **Implement LQIP (Low-Quality Image Placeholders).** Show a tiny blurred preview while the full image loads:99100 ```javascript101 // Generate LQIP at build time with sharp102 const sharp = require('sharp');103104 async function generateLQIP(inputPath) {105 const buffer = await sharp(inputPath)106 .resize(20) // 20px wide107 .blur(2)108 .jpeg({ quality: 20 })109 .toBuffer();110111 return `data:image/jpeg;base64,${buffer.toString('base64')}`;112 // ~200-400 bytes, inlineable in HTML113 }114 ```115116 ```html117 <!-- LQIP placeholder with fade-in transition -->118 <div class="image-container" style="aspect-ratio: 4/3;">119 <img120 src="data:image/jpeg;base64,/9j/4AAQSkZJ..."121 data-src="product-full.jpg"122 alt="Product"123 class="lqip-image"124 width="800"125 height="600"126 />127 </div>128129 <style>130 .image-container {131 overflow: hidden;132 }133 .lqip-image {134 width: 100%;135 height: 100%;136 object-fit: cover;137 filter: blur(20px);138 transform: scale(1.1);139 transition:140 filter 0.3s,141 transform 0.3s;142 }143 .lqip-image.loaded {144 filter: blur(0);145 transform: scale(1);146 }147 </style>148 ```1491504. **Use BlurHash for compact placeholders.** BlurHash encodes a placeholder in ~20-30 characters, decoded to a blurred preview on the client:151152 ```typescript153 // Server: encode at upload/build time using sharp + blurhash154 import { encode } from 'blurhash';155 import sharp from 'sharp';156157 async function generateBlurHash(imagePath: string): Promise<string> {158 const { data, info } = await sharp(imagePath)159 .raw()160 .ensureAlpha()161 .resize(32, 32, { fit: 'inside' })162 .toBuffer({ resolveWithObject: true });163 return encode(new Uint8ClampedArray(data), info.width, info.height, 4, 3);164 }165166 // Client: decode hash to pixels, render to <canvas> via ctx.putImageData()167 ```1681695. **Implement video poster optimization.** For video elements, use a poster image to avoid loading video data before play:170171 ```html172 <video poster="video-poster.webp" preload="none" width="1280" height="720" playsinline>173 <source src="video.mp4" type="video/mp4" />174 </video>175 ```176177 Set `preload="none"` to prevent the browser from downloading any video data. The poster image provides the visual preview. Combine with `loading="lazy"` on a facade image for below-fold videos.1781796. **Implement progressive image loading with CSS transitions.** Preload the full image in a `new Image()`, swap `src` on load, and animate with `filter: blur(20px)` transitioning to `filter: none` over 300ms. This smooths the placeholder-to-image transition without layout shift.1801817. **Configure the loading threshold.** Browsers load lazy images before they enter the viewport. Chrome uses a distance threshold that varies by connection speed (~1250px on 4G, ~2500px on slow 3G). For custom Intersection Observer implementations, set rootMargin based on image size and expected scroll speed:182183 ```typescript184 // Small thumbnails (fast to load): trigger closer185 const observer = new IntersectionObserver(callback, { rootMargin: '200px' });186187 // Large hero images (slow to load): trigger earlier188 const observer = new IntersectionObserver(callback, { rootMargin: '500px' });189 ```190191## Details192193### Native Lazy Loading Browser Behavior194195When `loading="lazy"` is set, the browser defers the image fetch until the image is within a distance threshold of the viewport. This threshold is not configurable by developers — it varies by browser and connection speed. Chrome on a fast connection starts loading images ~1250px before they enter the viewport. On slow 3G, this increases to ~2500px to compensate for longer download times. Images with `loading="lazy"` that are in the initial viewport on page load are loaded immediately (no deferral).196197### Worked Example: Medium Article Images198199Medium inlines a ~200-byte blurred LQIP as a base64 data URI. When the container approaches the viewport (Intersection Observer, 300px rootMargin), the full image loads and a CSS transition fades from blur to sharp over 300ms. Result: zero layout shift, immediate visual feedback, and ~95% of image bytes deferred.200201### Worked Example: Instagram Feed202203Each API response includes a 28-character BlurHash string rendered to a canvas as an instant placeholder. The actual image loads progressively (headers first, then increasing resolution scans). Result: colored blurred previews within 50ms of scrolling, zero layout shift, and perceived-instant loading.204205### Anti-Patterns206207**Lazy loading the LCP image.** Adding `loading="lazy"` to the hero image or any image visible without scrolling delays LCP by the intersection observer threshold plus download time. The LCP image should be eagerly loaded with `fetchpriority="high"`.208209**Using JavaScript lazy loading when native suffices.** Libraries like lazysizes add JavaScript overhead for functionality the browser provides natively. Use `loading="lazy"` for standard cases. Reserve JavaScript solutions for LQIP, BlurHash, or Intersection Observer patterns that native lazy loading cannot provide.210211**Placeholders that cause layout shift.** A placeholder with different dimensions than the final image causes Cumulative Layout Shift when swapped. Always set width, height, and aspect-ratio on containers. Placeholders must match the final image's aspect ratio.212213**Lazy loading all images indiscriminately.** Applying `loading="lazy"` to every image on the page, including above-the-fold images, delays rendering of critical content. Audit which images are in the initial viewport and exclude them from lazy loading.214215## Source216217- web.dev: Browser-level image lazy loading — https://web.dev/articles/browser-level-image-lazy-loading218- MDN: Lazy loading — https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading219- BlurHash — https://blurha.sh/220- lite-youtube-embed — https://github.com/niccoloborghesi/lite-youtube-embed221222## Process2232241. Read the instructions and examples in this document.2252. Apply the patterns to your implementation, adapting to your specific context.2263. Verify your implementation against the details and edge cases listed above.227228## Harness Integration229230- **Type:** knowledge — this skill is a reference document, not a procedural workflow.231- **No tools or state** — consumed as context by other skills and agents.232233## Success Criteria234235- Below-fold images use `loading="lazy"` and above-fold images do not.236- Video embeds use a facade pattern that loads the iframe only on interaction.237- Image placeholders (LQIP or BlurHash) are implemented for key images.238- No media lazy loading causes layout shift (containers have explicit dimensions).239- Initial page load transfers only images visible in the viewport.