mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
792 words
4 minutes
WebP vs AVIF Practical Guide: How to Choose Image Formats in Real Projects
2025-06-16

In frontend performance optimization, images usually take up the lion’s share. Many sites optimize JS and CSS to the extreme, yet still get stuck on LCP (Largest Contentful Paint). The root cause is often that the first-screen hero image is too large.

Both WebP and AVIF can significantly reduce image size, but if you only look at “which is smaller”, you can easily make the wrong decision. This article provides a complete solution from an engineering perspective: how to choose, how to implement, and how to verify regressions.

1. Unify Goals First: What Metrics Are You Optimizing?#

Image optimization isn’t about “small files”, it’s about real user experience:

  • LCP: First-screen large image loading speed.
  • CLS: Whether image size placeholders are stable.
  • The first-screen rendering path after TTFB.
  • CDN egress traffic costs.

If you are running a commercial site, you must also consider:

  • Is the build time controllable?
  • Is the image processing pipeline stable?
  • Is the operational complexity acceptable?

2. Core Differences Between WebP and AVIF#

2.1 Compression Ratio#

  • At the same subjective image quality, AVIF is usually smaller than WebP.
  • However, differences vary greatly across image types:
    • Photos: AVIF’s advantage is usually more pronounced.
    • Icons/Flat Illustrations: WebP is already excellent enough.

Conclusion: AVIF often saves more bandwidth, but not every image must be AVIF.

2.2 Encoding and Build Costs#

  • WebP encoding speed is usually faster, putting less pressure on CI/CD.
  • AVIF encoding is more CPU-intensive. Especially when batch processing large images, build times will increase significantly.

If your project builds multiple times a day and images are updated frequently, you must prioritize evaluating the build cost brought by AVIF.

2.3 Browser Compatibility and Fallback Strategies#

Modern browsers have very complete support for AVIF and WebP, but a fallback strategy should still be retained in engineering.

Recommended Approach: A three-tier fallback of AVIF -> WebP -> JPG/PNG using the <picture> tag.

<picture>
<source srcset="/img/hero.avif" type="image/avif">
<source srcset="/img/hero.webp" type="image/webp">
<img
src="/img/hero.jpg"
alt="Site Homepage Main Visual"
width="1200"
height="630"
loading="eager"
decoding="async"
>
</picture>

This code solves two things simultaneously:

  • Allows highly capable browsers to fetch smaller resources.
  • Allows environments that don’t support new formats to degrade stably.

3. When to Choose WebP vs. AVIF#

You can directly use this decision logic:

  • First-screen Critical Images (Hero Images)
    • Prefer AVIF (assuming acceptable quality).
    • Simultaneously retain WebP and JPG fallbacks.
  • Medium/Small Content Images
    • WebP as the default option; high cost-effectiveness.
  • Backend Admin Systems or Internal Tools
    • Prefer WebP to reduce build and maintenance complexity.
  • Large Volume of User-Uploaded Images
    • Standardize on WebP first, then append AVIF for hot/popular resources.

The engineering goal is not “Full-site AVIF”, but rather “Use AVIF where the ROI is highest”.

4. Practical: Using Sharp for Batch Multi-Format Generation#

If you have a Node project, Sharp is one of the most stable routes.

npm i -D sharp

Example script (scripts/image-build.mjs):

import fs from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';
const inputDir = 'img/source';
const outputDir = 'img/optimized';
await fs.mkdir(outputDir, { recursive: true });
const files = await fs.readdir(inputDir);
for (const file of files) {
const inputPath = path.join(inputDir, file);
const ext = path.extname(file).toLowerCase();
const base = path.basename(file, ext);
if (!['.jpg', '.jpeg', '.png'].includes(ext)) continue;
const image = sharp(inputPath).rotate();
await image
.clone()
.webp({ quality: 78 })
.toFile(path.join(outputDir, `${base}.webp`));
await image
.clone()
.avif({ quality: 52, effort: 4 })
.toFile(path.join(outputDir, `${base}.avif`));
await image
.clone()
.jpeg({ quality: 82, mozjpeg: true })
.toFile(path.join(outputDir, `${base}.jpg`));
}
console.log('image build done');

These parameters aren’t an absolute standard, but they suit most blogs/content sites as initial values.

5. Avoiding “Smaller Images but Worse Experience”#

Here are common anti-patterns:

  1. Only Compressing, Not Cropping: You compress a 3840px large image into AVIF, but the page only displays 800px. You are still wasting bandwidth.
  2. Ignoring Dimension Placeholders: Not writing width/height, causing page layout shifts (increased CLS) when images load.
  3. Lazy Loading First-Screen Images: Setting loading="lazy" on the main first-screen image will drag down LCP.
  4. One-Size-Fits-All Quality Parameters: A uniform quality value for all images might cause noticeable blurring in certain areas.

The correct approach is: differentiate scenarios first, then set parameters based on the scenario.

6. CDN and Edge Optimization Strategies#

If you use CDNs like Cloudflare, CloudFront, or Fastly, you can combine the following strategies:

  • Automatically negotiate formats based on the Accept header.
  • Create multi-size versions (srcset) for critical first-screen images.
  • Set longer cache periods for popular resources.
  • Use more conservative encoding strategies for low-traffic images to reduce build costs.

This balances “build-side pressure” with “transmission-side gains.”

7. An Executable Go-Live Process#

  1. Select 3 high-traffic page images as a pilot.
  2. Generate AVIF/WebP/JPG formats and integrate <picture>.
  3. Compare data for 7 days before and after going live:
    • Page LCP
    • Total image bandwidth
    • Error rates and compatibility feedback
  4. If results are stable, expand to other pages.

Do not refactor the entire site at once; run a closed loop with a small sample first.

8. Simplified Advice for Blog Sites#

If you are maintaining a Jekyll or lightweight blog:

  • Cover images and large in-text images: Three-format fallback.
  • Small icons: Prefer SVG.
  • Screenshot tutorial images: Prefer WebP (text edges are sharper).
  • Control the total number of images per article to avoid “too many images diluting the text’s value.”

Summary#

WebP and AVIF are not opposing technologies, but complementary ones.

  • WebP: Stable, fast, and “good enough,” suitable as a default strategy.
  • AVIF: Clear size advantages, suitable for critical resources and high-value pages.

Optimizing incrementally starting from core pages, then gradually expanding, is the only long-term maintainable performance strategy.

Share

If this article helped you, please share it with others!

WebP vs AVIF Practical Guide: How to Choose Image Formats in Real Projects
https://blog.levifree.com/posts/webp-vs-avif/
Author
LeviFREE
Published at
2025-06-16
License
CC BY-NC-SA 4.0

Some information may be outdated

Table of Contents