Image Optimization with AVIF and WebP: srcset, sizes and Quality

Choosing between AVIF, WebP and JPEG, quality testing, calculating srcset/sizes, the picture fallback and the lazy-loading mistake on the LCP image; WordPress size checks and WP-CLI commands.
Technical summary
Technology
AVIF, WebP, JPEG, HTML picture/srcset/sizes, fetchpriority, WordPress, WP-CLI
Topic
Image format, quality and responsive image delivery
Level
Intermediate
Prerequisites
  • Basic HTML and CSS knowledge
  • Administrator access to the WordPress media library
  • Ability to use browser developer tools
In this article8 sections

If a corporate page loads slowly, look at the images first. On corporate sites, the biggest item in page weight is almost always hero photos, client logos and project images; most of them are downloaded several times wider than their displayed size, in the wrong format and with the wrong priority. This guide covers format selection, quality settings, calculating srcset/sizes and prioritizing the LCP image, in a practical order of checks. For a general definition of the metrics, see the speed-up guide covering LCP, INP and CLS; here we work directly with images.

Comparing image formats

The format is chosen based on the image’s content. A photo and a flat-color diagram don’t benefit from the same compression approach; one has to preserve color gradients, the other sharp edges. The practical differences between the main formats found on corporate sites:

Format Strength Limitation Typical use
AVIF Usually the smallest file at the same perceived quality; alpha channel, HDR Slow, CPU-intensive encoding; not in older browsers Hero and content photos
WebP Lossy and lossless modes, alpha, fast encoding, very wide support Larger than AVIF at high quality General-purpose fallback and intermediate format
JPEG Universal support, progressive mode No alpha; blocking artifacts at low quality Final fallback
PNG Lossless, sharp edges Very large files for photos Screenshots, transparent graphics (lossless WebP is an alternative)
SVG Vector, sharp at any resolution Large DOM for complex drawings; needs a security check Logos, icons, simple illustrations

The waste we see most often in the field is logos and icons output as PNG or JPEG. If you have a vector source, use SVG, run the file through an optimization tool such as SVGO and strip the editor metadata. A warning: SVG can contain scripts. On systems where users can upload SVGs, restrict upload rights to trusted roles only.

Quality settings and compression

“Quality” numbers aren’t equivalent across formats. 80 for JPEG, 80 for WebP and 80 for AVIF give different results with different encoders. Instead of memorizing a fixed number, run a comparison on your own image set. Memorized numbers don’t work. The method we follow:

  1. Choose 5–10 images that represent your site: a photo with a human face, a finely detailed technical photo (cables, a rack), an image with flat-color areas and an image containing text.
  2. Produce output at several quality levels for each.
  3. Examine the images side by side at their real display size. Banding in flat color gradients and ringing around sharp edges are the first places to degrade.
  4. Record the lowest acceptable level per format and fix that value in your automation.

For command-line production, Google’s cwebp tool and avifenc, which comes with libavif, are widely used:

# WebP: quality on a 0–100 scale
cwebp -q 78 hero.jpg -o hero.webp

# AVIF (libavif 1.0 and later): -q quality, -s speed (0 slowest/most efficient, 10 fastest)
avifenc -q 60 -s 6 hero.jpg hero.avif

# Bulk conversion example (ImageMagick 7)
for f in *.jpg; do magick "$f" -quality 78 "${f%.jpg}.webp"; done

Check the source file too. Re-encoding a 6,000-pixel photo straight from the camera at high quality takes longer than a source scaled down to display size and brings no visible benefit. EXIF data (location, device information) is handled differently by different tools: cwebp doesn’t copy metadata by default, but avifenc and ImageMagick can carry over the metadata from the source file. Use the --ignore-exif and -strip options respectively for this, and check the output with exiftool. Location data in field photos isn’t just unnecessary bytes. It’s a privacy issue.

Calculating srcset and sizes correctly

srcset tells the browser the candidates of the same image at different widths, and sizes how many CSS pixels wide the image will be shown on the page. The browser multiplies the sizes value by the device pixel ratio (DPR) and picks a suitable candidate that meets it. Let’s do the calculation on a concrete layout:

  • The container is at most 1,200 px, the cards are in three columns with gaps between them: each card is about 384 CSS pixels.
  • Two columns on tablet, one column on mobile.
  • Candidate width needed on a laptop with a 2x screen: 384 × 2 = 768 pixels.
<img
  src="/img/proje-800.jpg"
  srcset="/img/proje-400.jpg 400w,
          /img/proje-800.jpg 800w,
          /img/proje-1200.jpg 1200w"
  sizes="(min-width: 1200px) 384px,
         (min-width: 768px) 50vw,
         100vw"
  width="1200" height="800"
  alt="Rack cabling in a server room"
  loading="lazy" decoding="async">

The media conditions in sizes are evaluated from left to right and the first match is used; write the widest condition first. The last value is the unconditional default. The width and height attributes let the browser know the aspect ratio in advance and prevent layout shift (CLS) while the image loads. With height: auto in CSS, responsive behavior isn’t affected.

Look for a balance in the number of candidates. If the difference between consecutive candidates is very small, cache hits drop and storage grows; if it’s very large, the browser downloads a bigger file than necessary. For most corporate layouts, 4–6 candidates between 400 and 2,000 pixels are enough.

Format fallback with the picture element

The standard way to offer different formats is the <picture> element. The browser evaluates the <source> elements in order and uses the first one whose type it supports; if none match, the <img> takes over. Accessibility text, size attributes and loading behavior are always defined on the <img>. alt isn’t written on source.

<picture>
  <source type="image/avif"
          srcset="/img/hero-800.avif 800w, /img/hero-1600.avif 1600w"
          sizes="100vw">
  <source type="image/webp"
          srcset="/img/hero-800.webp 800w, /img/hero-1600.webp 1600w"
          sizes="100vw">
  <img src="/img/hero-1600.jpg"
       srcset="/img/hero-800.jpg 800w, /img/hero-1600.jpg 1600w"
       sizes="100vw" width="1600" height="900"
       alt="Data center aisle" fetchpriority="high">
</picture>

The alternative is for the server or CDN to return a different format from the same URL by looking at the Accept request header (content negotiation). In that case the response must include Vary: Accept, and it must be verified that the CDN supports this behavior. Otherwise a cached AVIF file may go to a client that doesn’t support AVIF, and the image doesn’t show at all. For details on cache headers, see the Cache-Control and CDN headers guide.

Lazy loading and the LCP image

The native loading="lazy" attribute defers downloading images below the fold until the user gets close and reduces network contention on first load. When the same attribute is applied to the large image at the top of the screen, however, it directly delays LCP. This is the configuration mistake we come across most often in the field: a plugin or theme says “lazy-load all images” and the hero gets caught by the rule too. The right distribution:

Image position loading fetchpriority
Hero / LCP candidate eager (default) high
Small logos on the first screen eager not specified
Content images after scrolling lazy not specified
Hidden slides in a slider lazy low (optional)

If the LCP image is set with CSS background-image, the browser only discovers it after the stylesheet has been processed. In page builders, hero backgrounds are often set up this way. Discovery is delayed and LCP lengthens. Where possible, place the hero image as an <img>; if not, add a responsive preload:

<link rel="preload" as="image"
      href="/img/hero-1600.avif" type="image/avif"
      imagesrcset="/img/hero-800.avif 800w, /img/hero-1600.avif 1600w"
      imagesizes="100vw" fetchpriority="high">

The type attribute stops browsers that don’t support AVIF from downloading this file for nothing. Use preload only for the real LCP image. If everything is high priority, nothing is.

Auditing image sizes in WordPress

WordPress generates all registered intermediate sizes for every uploaded image and automatically adds srcset/sizes values to <img> tags in content. When the core sizes (thumbnail, medium, medium_large, large, and the 1,536 and 2,048-pixel sizes added in 5.3) combine with sizes added by themes and plugins, a single upload turns into dozens of files. Disk usage swells and backups take longer. See the current state first:

# List all registered image sizes
wp media image-size

# For a specific subsite in Multisite
wp media image-size --url=https://web.example.com

# Generate only missing sizes (try on staging first)
wp media regenerate --only-missing --yes

During the audit, look for answers to these questions in the console and templates:

  • Which theme/plugin registers which size, and is it actually used in templates?
  • Is there a suitable candidate for the widest displayed width (e.g. a full-width hero), or does the browser fall back to the original file?
  • Do slider and gallery components generate srcset, or do they output a single large URL?
  • Is WordPress’s big image threshold (big_image_size_threshold, 2,560 pixels by default) suitable for your workflow?
  • Does the image library on the server (Imagick or GD) support WebP and AVIF encoding? WordPress 6.5 and later accept AVIF uploads, but generating intermediate sizes depends on server support.

The last item is often skipped. If the library on the server can’t encode AVIF, WordPress can’t generate intermediate sizes and the theme outputs the original file; the problem is only noticed when a megabyte-sized image shows up in the Network panel.

To automatically convert intermediate sizes of uploaded JPEGs to WebP, the image_editor_output_format filter introduced in WordPress 5.8 can be used. The filter doesn’t change the original file; it only sets the format of the generated intermediate sizes. Doing the bulk conversion at the WordPress CDN layer (an image transformation service) is also an option; in that case verify that the cache key includes the format. For how Cloudflare, page cache and object cache work together, take a look at the Cloudflare, WP Rocket and Redis guide.

Measurement and verification

Verify the effect of a change by measurement, not guesswork. The order of checks:

  1. In the DevTools Network panel, look at the transferred size of each image with the Img filter; check in the Type column whether AVIF/WebP is actually being delivered.
  2. In the Elements panel, hover over the image and compare the “Rendered size” and “Intrinsic size” values. If the intrinsic value is clearly larger than the rendered value multiplied by the DPR, sizes is wrong.
  3. Use Lighthouse’s image delivery findings (“Improve image delivery” in current versions, “Properly size images” and “Serve images in next-gen formats” in older ones) as a starting list.
  4. In field data, monitor whether the LCP element is an image and its resource load delay.

A lab score is an indicator. Decisions are made with field data. If you want to run this measurement and improvement process on your corporate site in a planned way, see our web performance and Core Web Vitals service.

References: WHATWG HTML Standard – Images for the behavior of image elements, and the Google WebP documentation for WebP tools.

Frequently asked questions

Is there still a need to generate WebP when AVIF is available?

All current major browsers support AVIF, but older Safari versions and some embedded browsers may not. If you offer AVIF, WebP and JPEG in that order in a picture element, a supporting browser gets the smallest file and the image doesn’t break on older clients. If storage and processing time are limited, AVIF with a JPEG fallback is also a good enough start.

What happens if I don’t write the sizes attribute?

If the w descriptor is used in srcset and sizes isn’t given, the browser assumes the image will be shown at the viewport width (100vw). In a three-column grid, that means downloading a file about three times wider than needed. You won’t see anything broken on screen; the bandwidth quietly goes to waste.

Why is using loading=”lazy” on the LCP image a problem?

Lazy loading makes the browser request the image only after layout has been calculated and the image is found to be near the viewport. For the large image at the top of the screen, that means a delayed request and a longer LCP. The LCP candidate image should be loaded eagerly and prioritized with fetchpriority=”high”.

What happens to old images after adding a new size in WordPress?

New sizes defined with add_image_size are only generated for images uploaded from then on. For existing images, run the wp media regenerate command with WP-CLI, preferably with the –only-missing parameter and in a test environment first. Back up the uploads directory before the operation; only then is rolling back easy.

Support

Contact us for support or a discovery session on this topic.

Contact form
[email protected]

Eretek Web

We build and maintain corporate websites, WordPress and CMS platforms, intranet and SharePoint portals, document management, and form and approval workflows, and keep them secure and up to date.

Knowledge Center

Other articles