JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
PrevNext
performance
junior
images

How do you optimize images for web performance?

images
optimization
lazy-loading
webp
srcset
Quick Answer

Optimize images by: using modern formats (WebP, AVIF), proper sizing for display dimensions, lazy loading below-the-fold images, using responsive images with srcset, and compressing without visible quality loss.

Detailed Explanation

Image Optimization Techniques:

  1. Modern Formats:

    • WebP: 25-35% smaller than JPEG
    • AVIF: Even smaller, newer support
    • Use <picture> for fallbacks
  2. Proper Sizing:

    • Don't serve 2000px for 200px display
    • Generate multiple sizes
    • Use srcset for responsive
  3. Lazy Loading:

    • loading="lazy" attribute
    • Only load when near viewport
    • Eager load above-the-fold
  4. Compression:

    • Balance quality vs size
    • Use tools like Squoosh, ImageOptim
    • Automate in build process

Code Examples

Responsive images with srcset
<!-- Basic srcset for different sizes -->
<img 
  src="image-800.jpg"
  srcset="
    image-400.jpg 400w,
    image-800.jpg 800w,
    image-1200.jpg 1200w
  "
  sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
  alt="Description"
  loading="lazy"
  decoding="async"
  width="800"
  height="600"
/>

<!-- Picture element for format fallbacks -->
<picture>
  <source type="image/avif" srcset="image.avif" />
  <source type="image/webp" srcset="image.webp" />
  <img src="image.jpg" alt="Description" loading="lazy" />
</picture>

<!-- Art direction with different images -->
<picture>
  <source media="(max-width: 600px)" srcset="mobile-hero.jpg" />
  <source media="(max-width: 1000px)" srcset="tablet-hero.jpg" />
  <img src="desktop-hero.jpg" alt="Hero" />
</picture>

Resources

Web.dev - Optimize images

article

Squoosh - Image compression

docs

Related Questions

What are Core Web Vitals and why do they matter?

junior
metrics

What is lazy loading and how do you implement it?

junior
loading
Previous
What are Core Web Vitals and why do they matter?
Next
What is lazy loading and how do you implement it?