Image Optimization for Websites: WebP vs AVIF Compared

WebP vs AVIF for website images: file size, quality, browser support and encode time, plus responsive images, lazy loading and dimensions that stop CLS.

· BugViso Team

13 min read

WebP vs AVIF: WebP is the safe default for website image optimization, and AVIF compresses smaller but encodes slower. Serve each image in a modern format, at the size it is displayed, with the right loading priority. Fix the LCP image first (preload it, never lazy-load it), then lazy-load what sits below the fold.

This guide compares WebP and AVIF, then covers compression quality, responsive srcset and sizes, lazy loading, fetchpriority and explicit dimensions to prevent layout shift.


The Performance Stakes: How Un-Optimized Images Hurt LCP and Conversion Rates

Visual assets directly dictate the outcome of Google's Core Web Vitals assessments. On the vast majority of content pages, e-commerce stores and marketing landing pages, the element selected as the Largest Contentful Paint (LCP) is an <img> tag or a CSS background image.

LCP is one of the three metrics in Core Web Vitals explained. For Shopify specifically, the hero-image fix (image_url widths, eager loading, fetchpriority) is fix 7 in our Shopify speed optimization guide.

Architectural IssueDownstream MetricUser Impact
Monolithic multi-megabyte JPEGSlow LCP on mobile connectionsSlow visual load, visitors leave
Missing Dimensions (Width/Height)Higher CLSLayout jumps during image decode
Lazy Loading Hero ImageDelayed LCPArtificial network discovery delay
Desktop Image on Mobile ViewportsWasted cellular dataSlower load, battery drain

As a worked example, a 2.4MB hero graphic on Lighthouse's simulated mobile connection (1.6 Mbps) needs about 12 seconds to download (2.4MB × 8 ÷ 1.6 Mbps). No server or JavaScript tuning can bring that page to a good LCP (2.5 seconds or less).

To understand how asset delivery timing interacts with overall page speed, review our analysis on how to improve Largest Contentful Paint (LCP).


Modern Image Formats Compared: JPEG vs PNG vs WebP vs AVIF vs SVG

Selecting the appropriate encoding format for each asset type is the foundation of image optimization. Delivering a photographic graphic in PNG format rather than AVIF or WebP usually costs a large file size penalty.

Modern Web Image Format Matrix

FormatBest useCompressionTransparencyBrowser support
SVGLogos, icons, UIVector (XML)YesAll browsers
JPEGLegacy fallbackLossyNoAll browsers
PNGDetailed graphicsLosslessYesAll browsers
WebPPhotos, general useLossy and losslessYesAll current browsers
AVIFPhotos, best compressionLossy and losslessYes (and HDR)Current browsers; check caniuse

1. Scalable Vector Graphics (SVG)

SVGs are XML-based vector descriptions composed of mathematical points, lines, and curves. Because SVGs scale infinitely to any display resolution without rasterization artifacts, they are the mandatory standard for logos, UI icons, and structural diagrams. SVGs should always be minified (stripping editor metadata) and compressed via Gzip or Brotli at the server level.

2. WebP (Google VP8 Codec)

Developed by Google, WebP provides superior lossy and lossless compression for photographic imagery. Google reports that lossy WebP files are 25% to 34% smaller than comparable JPEGs at equivalent SSIM quality (WebP documentation) and support 8-bit alpha transparency with significantly smaller byte footprints than PNGs.

3. AVIF (AV1 Image File Format)

AVIF represents the current state of the art in open-source web image compression. Derived from the AV1 video codec by the Alliance for Open Media (AOMedia), AVIF usually produces the smallest files of the three for photographs at similar visual quality, though the gain over WebP varies by image, so test your own.

According to Google's guide on choosing the right image format, AVIF excels at preserving fine details, high-contrast text overlays, and dark gradients without the blocky chroma ringing common in older compression codecs.

What to expect when converting a photograph

For the same photo, an optimized JPEG is far smaller than the PNG original, WebP is smaller again, and AVIF is smaller still. The exact savings depend on the image, so measure your own files with Squoosh or cwebp/avifenc rather than trusting a headline number.


Compression Science: Finding the Quality 80 Sweet Spot

Image compression algorithms work by discarding spatial frequency data that the human eye struggles to perceive (lossy compression) or by finding more efficient mathematical representations of pixel data (lossless compression).

A common mistake in media workflows is exporting images at 100% quality. The relationship between visual quality and byte size is steeply non-linear.

Quality versus file size

File size falls steeply as quality drops from 100, while visible loss stays small until the 70s. Below about 65, banding and blocking artifacts start to show.

Test a few values on your own images.

The Quality 80 Benchmark

For both WebP and AVIF encoders, Quality 80 represents the optimal inflection point:

  • Reducing quality from 100 to about 80 typically cuts file weight sharply with little visible difference; check a Structural Similarity Index Measure (SSIM) or compare side by side on your own images.
  • Dropping quality below 65 yields diminishing file size returns while introducing noticeable color banding, halo artifacts around text, and muddy textures.

Responsive Image Architecture: <picture>, srcset, and sizes

Delivering a full-resolution 1920px desktop hero image to a mobile user with a 390px viewport wastes hundreds of kilobytes of network bandwidth and forces the mobile browser to downscale the image on the GPU during rendering.

It's one of the main reasons LCP is slow on mobile but fast on desktop.

Resolution Mismatch On Mobile

  • Anti-pattern (one fixed desktop asset): a 390px-wide phone downloads the 1920px image and throws away most of its pixels.
  • Responsive srcset: the phone downloads a 480px file and the desktop a 1440px file, so each device gets the resolution its screen needs.

Implementing Responsive Markup with <picture> and srcset

Under the MDN <picture> element specification, you can combine progressive format negotiation (serving AVIF to modern browsers with WebP/JPEG fallbacks) with responsive resolution switching:

html
<picture>
  <!-- 1. Serve Next-Gen AVIF for Modern Browsers -->
  <source 
    type="image/avif" 
    srcset="/img/hero-480.avif 480w, /img/hero-800.avif 800w, /img/hero-1400.avif 1400w"
    sizes="(max-width: 768px) 100vw, 1400px"
  />

  <!-- 2. Serve WebP as High-Compatibility Modern Fallback -->
  <source 
    type="image/webp" 
    srcset="/img/hero-480.webp 480w, /img/hero-800.webp 800w, /img/hero-1400.webp 1400w"
    sizes="(max-width: 768px) 100vw, 1400px"
  />

  <!-- 3. Final Universal Fallback <img> Tag (Always Required) -->
  <img 
    src="/img/hero-1400.jpg" 
    width="1400" 
    height="788" 
    alt="Cloud Analytics Infrastructure Dashboard" 
    class="responsive-hero-media"
    loading="eager"
    fetchpriority="high"
  />
</picture>

<style>
.responsive-hero-media {
  width: 100%;
  height: auto;
  aspect-ratio: 1400 / 788;
  display: block;
}
</style>

How sizes Informs the Browser:

  1. The sizes attribute tells the browser's speculative HTML parser how wide the image will render on the screen before CSS stylesheets have finished downloading.
  2. The browser inspects the device's physical viewport width and Device Pixel Ratio (e.g., 2x Retina), calculates the needed pixel width, and selects the optimal URL from the srcset candidates.

Native Lazy Loading (loading="lazy") and Above-the-Fold Rules

Native lazy loading defers the download of off-screen images until the user scrolls near their position in the viewport.

Native Lazy Loading Scroll Thresholds

  • ================ CURRENT VISIBLE VIEWPORT ================
  • Hero Image: loading="eager" + fetchpriority="high"
  • (Downloaded immediately with Highest Priority on page load)
  • SCROLL BUFFER: Browser initiates download ~800px ahead of scroll
  • Feature Section Image: loading="lazy"
  • Customer Testimonial Image: loading="lazy"
  • Footer Logo Gallery: loading="lazy"
  • (Zero bytes transferred until user actually scrolls down the page)

The Fatal Anti-Pattern: Lazy Loading the Hero Image

According to the MDN HTMLImageElement loading attribute, setting loading="lazy" instructs the browser to delay fetching the resource until the layout engine finishes rendering the DOM and confirms that the element intersects the viewport.

Hero Image Lazy Loading Penalty

  • CORRECT (Eager Hero):
  • HTML Parser discovers <img> → [Immediate Network Request: 0ms] Correct (eager hero):
  1. The HTML parser discovers the <img> and issues an immediate network request at 0ms.
  2. LCP resolves at 1.2s.

Incorrect (lazy hero anti-pattern):

  1. The HTML parser encounters loading="lazy".
  2. It waits for the CSS download, then for layout calculation.
  3. It confirms the image is in the viewport at the 1.1s mark, and only then dispatches the image request.
  4. LCP is delayed to 2.6s, which fails Core Web Vitals.

The Golden Rule of Image Delivery:

  • Above-the-Fold Images (Hero, Logo, Product Banner): Always set loading="eager" and pair with fetchpriority="high".
  • Below-the-Fold Images (Galleries, Product Cards, Footer): Always set loading="lazy".

Accelerating Critical Assets with fetchpriority="high" and Preloading

The three LCP hints are compared in depth in fetchpriority, preload and preconnect. On WordPress, the matching setup is item 5 of Core Web Vitals on WordPress.

By default, web browsers assign standard image requests a "Low" or "Medium" network priority, reserving "High" priority for render-blocking CSS and JavaScript files.

To prevent your primary hero image from waiting behind secondary scripts, use the MDN fetchPriority API to elevate the asset's priority in the network queue:

html
<!-- Elevate Hero Image to High Network Priority -->
<img 
  src="/img/hero.avif" 
  width="1200" 
  height="675" 
  alt="Platform Overview" 
  fetchpriority="high" 
  loading="eager" 
/>

Preloading Responsive Hero Images in Document <head>

If your hero image is rendered via CSS or dynamic components, inform the browser's pre-loader immediately inside the document <head>:

html
<head>
  <!-- Preload Responsive Hero Asset -->
  <link 
    rel="preload" 
    as="image" 
    href="/img/hero-desktop.avif" 
    type="image/avif" 
    media="(min-width: 769px)" 
    fetchpriority="high" 
  />
  <link 
    rel="preload" 
    as="image" 
    href="/img/hero-mobile.avif" 
    type="image/avif" 
    media="(max-width: 768px)" 
    fetchpriority="high" 
  />
</head>

Eliminating Cumulative Layout Shift (CLS) with Explicit Dimensions and CSS

When an image binary finishes downloading, the browser resizes the element from its initial un-rendered height ($0\text{px}$) to its intrinsic dimensions, shifting all subsequent content down the screen.

Before (the shift occurs): the unsized <img> takes 0px of height on the first paint, so the header and the primary action button sit directly together.

When the image binary finishes loading, the container expands (for example to 400px) and the button jumps down by that amount, a severe CLS penalty.

The Solution: Intrinsic Aspect Ratios

Always include explicit raw pixel width and height attributes directly on HTML <img> elements. Modern browsers automatically derive the element's aspect ratio from these attributes before the image binary arrives, reserving the exact layout space in advance.

html
<!-- Explicit HTML dimensions establish intrinsic aspect ratio -->
<img 
  src="/img/analytics-chart.webp" 
  width="800" 
  height="450" 
  alt="Quarterly Performance Chart" 
  class="fluid-media-box" 
/>

<style>
.fluid-media-box {
  width: 100%;
  height: auto;
  /* Ensures aspect ratio calculation remains stable during responsive resizing */
  aspect-ratio: 800 / 450;
  display: block;
}
</style>

For complete technical remediation patterns covering fonts, dynamic injected ads, and media containers, read our complete guide on how to fix Cumulative Layout Shift (CLS).


How BugViso Automates Image Auditing and Compression Simulation

Manually identifying oversized images, verifying missing alt attributes, and calculating format conversion savings across hundreds of dynamic subpages is impractical for growing digital properties.

When you run an automated website scan with BugViso, the backend auditing worker performs a deep-dive analysis of your media pipeline:

  1. Intelligent Asset Compression Simulation: BugViso identifies your largest hero and raster images (>50KB) and re-encodes them through its image processing pipeline to WebP (and AVIF) at Quality 80, quantifying the exact kilobyte savings achievable across your site.
  2. Image SEO and CLS Protection: The engine inspects the live rendered DOM, identifying all images lacking explicit width and height dimensions, detecting missing or empty alt attributes, and warning against non-descriptive filenames (e.g., image_32.png, hash strings).
  3. Concurrent Asset Link Integrity: BugViso concurrently validates every image src and srcset candidate target across all crawled pages, flagging 404 broken assets and insecure mixed-content (http://) requests.
  4. Ranked fix list: Media findings appear in the ranked fix list with asset URLs, current weights and simulated byte savings, in the web report and the PDF.

You can see every rule BugViso applies in its LCP, INP and CLS speed test.


Common Mistakes in Website Image Optimization

Avoid these frequent implementation errors when executing an image optimization strategy:

Common MistakeConsequence
Lazy Loading the Hero Image Delays LCP by 800ms - 1500ms
Missing Width/Height Tags Triggers severe Cumulative Layout Shift
Oversized Desktop Images Wastes cellular data on mobile screens
Over-Compressing (< Q65) Creates noticeable blocky artifacts

Compression is only half of image quality; descriptive alt text matters for accessibility and image search, as covered in how to write alt text.

1. Applying loading="lazy" Globally via CMS Plugins

Many CMS optimization plugins offer a toggle to "Enable Lazy Loading" that applies loading="lazy" indiscriminately to every image on the page, including the above-the-fold hero graphic. This single configuration error frequently turns a passing LCP score into a failing score.

2. Relying Solely on CSS Resizing

Setting img { width: 100%; max-width: 400px; } in CSS changes how the image renders visually on the screen, but it does not change the number of bytes transferred over the network.

Delivering a 3000px wide image file to a 400px container still forces the browser to download the entire multi-megabyte payload.

3. Using Non-Descriptive Image Filenames

Uploading images named IMG_5892.jpg or hero-v2-final.png misses valuable image SEO context. Use descriptive, hyphen-separated filenames containing relevant keywords (e.g., cloud-database-architecture-diagram.webp) to assist search engines in understanding visual content.


Frequently Asked Questions About Image Optimization

These answers cover what readers ask most about WebP, AVIF and image optimization.

Is AVIF better than WebP for website images?

Yes, in terms of compression efficiency: AVIF usually produces smaller files than WebP and JPEG at equivalent visual quality, with the gain depending on the image. WebP enjoys slightly broader legacy browser support (check Can I use), so modern best practice is using the HTML <picture> element to serve AVIF with a WebP fallback.

Why should I never lazy load the primary hero image?

Lazy loading instructs the browser to delay downloading an image until layout calculation confirms it intersects the viewport.

Because the hero image is already visible at the top of the page, lazy loading creates an unnecessary delay of 800ms to 1.5 seconds, directly inflating your Largest Contentful Paint (LCP) score.

Does image optimization improve Google search rankings?

Yes. Optimizing images directly improves Core Web Vitals metrics (LCP and CLS), which are official components of Google's Page Experience ranking signals. Additionally, descriptive filenames, fast-loading media, and proper alt attributes enhance visibility in Google Image Search.

How do I prevent image layout shifts during page loading?

Always include explicit raw pixel width and height attributes on HTML <img> elements, paired with responsive CSS rules (width: 100%; height: auto; aspect-ratio: attr(width) / attr(height);). This allows the browser to compute the exact aspect ratio and reserve layout space before the image file finishes downloading.

A compression quality setting of 80 (or 75–82) provides the optimal balance between visual fidelity and file size reduction. Compare the result with the original on your own images before you settle on a number.


Summary and Action Plan

Modern image optimization requires a complete architectural workflow. Six steps cover it:

  1. Convert photographic assets to AVIF and WebP.
  2. Export at Quality 80.
  3. Deliver responsive resolutions using srcset and sizes.
  4. Set loading="eager" with fetchpriority="high" on above-the-fold hero graphics.
  5. Lazy load below-the-fold media.
  6. Supply explicit dimension attributes to eliminate layout shifts.

To find media bottlenecks across a site, sign in and run a BugViso scan; it simulates WebP/AVIF compression savings and audits image SEO across the crawl.

Written by

· BugViso Team

Kazi writes BugViso’s guides on website audits, Core Web Vitals, technical SEO, accessibility and AI search. The data in them comes from audits BugViso runs in a real Chromium browser, including our 219-site study of website health.

Found this useful? Share it.

Summarise with AI

Open this guide in your assistant.

Follow BugViso

New guides and audit data as we publish them.

AI visibility tracker

Is your brand in AI answers?

See how often AI assistants mention you, cite your site and rank you against your competitors.

  • ChatGPT
  • Gemini
  • Perplexity
  • Claude
  • AI Overviews
See how it works

See where your site stands

Run a free BugViso audit for SEO, speed, accessibility and AI search readiness — with fixes you can ship today.