Images often account for most page weight. This guide covers optimization techniques for faster loading.
Modern Image Formats#
Format Comparison#
| Format | Best For | Browser Support |
|---|---|---|
| WebP | Photos, graphics | 97%+ |
| AVIF | High compression | 85%+ |
| JPEG | Photos (fallback) | 100% |
| PNG | Transparency | 100% |
| SVG | Icons, illustrations | 100% |
Picture Element for Fallbacks#
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Description" width="800" height="600">
</picture>Responsive Images#
1<img
2 srcset="
3 image-400.jpg 400w,
4 image-800.jpg 800w,
5 image-1200.jpg 1200w
6 "
7 sizes="(max-width: 600px) 100vw,
8 (max-width: 1200px) 50vw,
9 800px"
10 src="image-800.jpg"
11 alt="Description"
12>Lazy Loading#
1<!-- Native lazy loading -->
2<img src="image.jpg" loading="lazy" alt="Description">
3
4<!-- Intersection Observer for more control -->
5<script>
6const observer = new IntersectionObserver((entries) => {
7 entries.forEach(entry => {
8 if (entry.isIntersecting) {
9 const img = entry.target;
10 img.src = img.dataset.src;
11 observer.unobserve(img);
12 }
13 });
14});
15
16document.querySelectorAll('img[data-src]').forEach(img => {
17 observer.observe(img);
18});
19</script>Next.js Image Optimization#
1import Image from 'next/image';
2
3function ProductImage({ product }) {
4 return (
5 <Image
6 src={product.imageUrl}
7 alt={product.name}
8 width={800}
9 height={600}
10 placeholder="blur"
11 blurDataURL={product.blurHash}
12 priority={false}
13 />
14 );
15}Build-Time Optimization#
1// sharp for server-side processing
2import sharp from 'sharp';
3
4async function optimizeImage(input: Buffer): Promise<Buffer> {
5 return sharp(input)
6 .resize(1200, 800, { fit: 'inside', withoutEnlargement: true })
7 .webp({ quality: 80 })
8 .toBuffer();
9}CDN Configuration#
# Cache images for 1 year
location ~* \.(jpg|jpeg|png|gif|webp|avif|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}Always specify dimensions, use modern formats with fallbacks, and lazy load below-the-fold images.