Skip to content

Image Optimization — WebP, AVIF, Lazy Loading Guide

DodaTech Updated 2026-06-23 6 min read

In this tutorial, you will learn how to optimize images for the web using next-gen formats like WebP and AVIF, Lazy Loading techniques, responsive image sets, and compression pipelines. Images account for over 50 percent of the average page weight, making optimization the highest-ROI performance task. DodaZIP reduced its landing page weight by 62 percent simply by converting all images to WebP with appropriate quality settings.

What You Will Learn

  • How to convert images to WebP and AVIF with optimal quality settings
  • How to implement Lazy Loading using the native loading attribute and Intersection Observer
  • How to use srcset and picture elements for responsive images
  • How to build an automated image optimization pipeline

Why It Matters

Every kilobyte of image data that loads before the user sees it wastes bandwidth and delays LCP. Google uses image weight and proper formatting as direct ranking signals. DodaTech products like Durga Antivirus Pro include optimized icons and screenshots that load instantly even on slow connections.

Real-World Use Case

The DodaTech documentation site hosted 3000 screenshots in PNG format totaling 450MB. After converting to WebP at quality 80 and adding Lazy Loading, total image weight dropped to 120MB and median page LCP improved from 3.2 seconds to 1.4 seconds.

Prerequisites

You should understand HTML image tags and CSS background-image properties. Familiarity with the command line and image editing tools is helpful. Knowledge of Core Web Vitals is recommended.

Step-by-Step Tutorial

Step 1: Convert Images to WebP

WebP offers 25 to 35 percent smaller file sizes than JPEG at equivalent quality. Use the Google cwebp command-line tool or online converters.

# Install cwebp on Ubuntu
sudo apt-get install webp

# Convert a JPEG image to WebP
cwebp -q 80 input.jpg -o output.webp

# Convert a PNG with transparency
cwebp -q 85 -alpha_q 70 input.png -o output.webp

Expected output: A WebP file that is 60 to 75 percent of the original JPEG size with no visible quality loss.

Step 2: Use AVIF for Even Better Compression

AVIF provides 50 percent better compression than JPEG and supports HDR and transparency. Not all browsers support it, so use it as a fallback.

# Convert to AVIF using avifenc (libavif)
sudo apt-get install libavif-bin
avifenc --min 0 --max 63 -s 8 input.jpg -o output.avif

Expected output: An AVIF file that is typically 50 percent smaller than JPEG at the same visual quality. Compare the file sizes: JPEG 120KB, WebP 85KB, AVIF 55KB.

Step 3: Implement Responsive Images with srcset

The srcset attribute allows the browser to choose the best image size based on the viewport width and device pixel ratio.

<img
  src="photo-800.webp"
  srcset="
    photo-400.webp 400w,
    photo-800.webp 800w,
    photo-1200.webp 1200w,
    photo-2000.webp 2000w
  "
  sizes="(max-width: 600px) 100vw, (max-width: 1200px) 80vw, 1200px"
  alt="DodaTech product screenshot"
  loading="lazy"
>

Expected behavior: On a 375px mobile screen, the browser downloads photo-400.webp (approximately 15KB) instead of photo-2000.webp (approximately 120KB).

Step 4: Implement Lazy Loading

Native Lazy Loading using the loading="lazy" attribute defers offscreen images until the user scrolls near them.

<!-- Above the fold: eager load (default) -->
<img src="hero.webp" alt="Hero banner" importance="high" />

<!-- Below the fold: lazy load -->
<img src="gallery-1.webp" alt="Gallery image" loading="lazy" />

For older browser support, use the Intersection Observer API.

// Intersection Observer for lazy loading
document.addEventListener('DOMContentLoaded', () => {
  const images = document.querySelectorAll('img[data-src]');
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.removeAttribute('data-src');
        observer.unobserve(img);
      }
    });
  });
  images.forEach(img => observer.observe(img));
});

Expected behavior: Images below the fold show the data-src attribute in the DOM but only start downloading when the user scrolls them into view.

Step 5: Use the Picture Element for Format Fallbacks

The <picture> element lets you serve AVIF to compatible browsers and fall back to WebP or JPEG for others.

<picture>
  <source srcset="photo.avif" type="image/avif" />
  <source srcset="photo.webp" type="image/webp" />
  <img src="photo.jpg" alt="Fallback JPEG image" />
</picture>

Expected behavior: Chrome and Firefox load photo.avif, Safari loads photo.webp, and older browsers load photo.jpg.

Step 6: Automate Image Optimization with a Build Pipeline

Use a task runner or build tool to automate optimization so every image is processed before deployment.

// Gulp task for image optimization
const gulp = require('gulp');
const webp = require('gulp-webp');
const imagemin = require('gulp-imagemin');

gulp.task('images', () => {
  return gulp.src('src/images/**/*.{jpg,png}')
    .pipe(imagemin([
      imagemin.mozjpeg({quality: 80}),
      imagemin.optipng({optimizationLevel: 3})
    ]))
    .pipe(gulp.dest('dist/images'))
    .pipe(webp({quality: 80}))
    .pipe(gulp.dest('dist/images'));
});

Expected output: All images in the dist/images directory are compressed JPEG/PNG plus WebP versions.

Learning Path

flowchart LR
  A[Caching Strategies] --> B[Image Optimization]
  B --> C[JavaScript Bundle Optimization]
  B --> D[CSS Performance]
  C --> E[Critical Rendering Path]
  
  style B fill:#4f46e5,color:#fff
  style A fill:#6366f1,color:#fff
  style C fill:#6366f1,color:#fff

Common Errors

  1. Using JPEG quality 100: Quality 100 produces enormous files with no visible benefit. Quality 80 to 85 is visually lossless for photographs.

  2. Not specifying image dimensions: Omitting width and height causes layout shifts (CLS). Always set dimensions or use the aspect-ratio CSS property.

  3. Applying Lazy Loading to the hero image: The hero image is likely the LCP element and should load eagerly, not lazily.

  4. Serving oversized images for mobile: An image rendered at 400px wide should not be served as a 4000px source. Use srcset to serve appropriately sized versions.

  5. Using PNG for photographs: PNG is a lossless format meant for graphics with transparency. Use JPEG, WebP, or AVIF for photographs to save 70 to 80 percent in file size.

  6. Ignoring the alt attribute for performance: While alt text does not affect image weight, missing alt attributes hurt Accessibility scores which are part of Lighthouse and SEO rankings.

Practice Questions

  1. What is the typical file size reduction when converting JPEG to WebP?
  2. How does the loading=lazy attribute work in modern browsers?
  3. What is the purpose of the sizes attribute in srcset?
  4. Why should you avoid PNG for photographic images?
  5. How does the picture element support format fallbacks?

Answers: 1. 25 to 35 percent smaller at equivalent quality. 2. It defers loading of offscreen images until the user scrolls near them. 3. It tells the browser the rendered width of the image at different viewport sizes so it picks the correct source. 4. PNG is lossless and produces files 3 to 5 times larger than JPEG for photographs. 5. It allows multiple source elements with different type attributes; the browser uses the first format it supports.

Challenge

Write a Shell Script that scans a directory for JPEG and PNG images, converts them to WebP at quality 80, creates AVIF versions at quality 60, and generates corresponding HTML <picture> elements with the correct srcset attributes for each image.

FAQ

What is the difference between WebP and AVIF?

WebP is supported by 97 percent of browsers and offers 25-35 percent better compression than JPEG. AVIF offers 50 percent better compression but has approximately 80 percent browser support.

Should I use lossy or lossless WebP?

Use lossy WebP for photographs and complex graphics. Use lossless WebP only for images requiring exact pixel reproduction, like screenshots with text or logos.

Does Lazy Loading improve SEO?

Yes, Google considers page speed a ranking factor. Lazy Loading reduces initial page weight, improving LCP and overall performance scores which indirectly benefit SEO.

Can I optimize SVGs?

SVGs are vector graphics and do not benefit from the same compression as raster images. Optimize SVGs by removing unused metadata, minifying the code, and compressing with gzip.

What tools does DodaTech recommend for image optimization?

DodaTech uses cwebp for WebP conversion, avifenc for AVIF, and the Squoosh web app for quick single-image optimization. For batch processing, we use a Gulp pipeline similar to the example above.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro