Skip to content

No. 26Performance9 min read2,468 words

Image optimization for fast websites: a practical guide

Image optimization for developers and site owners: when to use AVIF or WebP, responsive sizing, lazy loading and the next/image settings that fix LCP.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01Images are usually the heaviest bytes on a page and the hero image is usually the LCP element, so image work is the highest-payoff performance fix on most sites.
  2. 02Serve WebP as the default and AVIF where you can afford the slower encode; keep SVG for logos and icons, and never use PNG for photographs.
  3. 03Give every image width and height (or a CSS aspect-ratio) to prevent layout shift, and an accurate sizes attribute so phones do not download desktop-width files.
  4. 04Lazy-load everything below the fold, but never the LCP image: load it eagerly with fetchpriority="high". In Next.js 16, the priority prop is deprecated in favour of preload or fetchPriority.
  5. 05Fix the three or four heaviest images first and measure after each change; most sites get the bulk of the improvement there.
On this page ยท 10

Image optimization means serving each image in the smallest format, at the size it actually renders, and loading it at the right moment: eagerly for the hero, lazily for everything else. Do those three things and most "slow" sites become fast without touching their JavaScript. Open the network tab on almost any slow site and the story is the same: a handful of images that each weigh more than the rest of the page combined.

You can spend a week shaving milliseconds off a bundle, but a single multi-megabyte hero photo undoes all of it before the browser has parsed your code. Image optimization is the highest-impact performance work most teams never finish, so here is how we do it properly on every project.

Why images dominate your performance budget

On most pages, the Largest Contentful Paint (LCP) element is an image: the hero, the article cover, the product photo at the top of the page. If that one file arrives late, your LCP is poor no matter how fast everything else is, and LCP is one of the three metrics in our Core Web Vitals checklist. Our web performance statistics page collects the HTTP Archive figures on how often images are the LCP element, and how many sites still get the basics wrong.

Photos straight out of a phone camera or a stock library are routinely several megabytes. On a mobile connection that is seconds of download for one file. Repeat that for the dozen images on a landing page and you get a site that feels broken even though nothing is technically wrong.

The good news is that images are also the easiest big win. You rarely need to refactor anything. You change formats, dimensions and loading behaviour, and the page gets faster. On a store, that speed shows up in conversion, which we cover in how site speed affects e-commerce revenue.

Images affect two of the three Core Web Vitals directly:

Image problemMetric it hurtsWhy
Hero image too heavy or found lateLCPThe largest element finishes rendering late
Hero image lazy-loadedLCPThe browser deliberately waits before fetching it
Images without width and heightCLSContent jumps when the image arrives and takes up space
Dozens of images decoding at onceINP (indirectly)Main-thread work competes with user input during load

Pick the right image format

Format choice alone can cut file size dramatically before you touch dimensions. The MDN image format guide covers support in detail; this is how we choose.

FormatUse it forAvoid it forNotes
AVIFPhotos and complex images that are encoded once and cachedPipelines that encode on every requestUsually the smallest; slower to encode
WebPThe default for photos and most raster imagesNothing much in 2026Supported by every current browser
JPEGFallback for very old clients, emailAnything you can serve as WebPUniversal but larger
PNGLossless screenshots, images needing exact pixelsPhotographsPhotos as PNG balloon in size
SVGLogos, icons, illustrations, chartsPhotographsScales infinitely, often tiny
Video (MP4/WebM)Anything you were going to make a GIFStatic imagesFar smaller than animated GIF

On AVIF versus WebP, the Next.js documentation puts it plainly: AVIF generally takes longer to encode but compresses smaller than WebP, and Next.js still recommends WebP for most use cases. That is our default too. We turn AVIF on when images are encoded at build time or cached hard on a CDN, so the encode cost is paid once.

Animated GIFs deserve a special mention. They are one of the least efficient ways to put motion on a page. Replacing GIFs with looping, muted video usually cuts the weight by an order of magnitude and looks better.

Serving modern formats with a fallback

The browser-native way to offer modern formats is the picture element. The browser uses the first source it can decode:

<picture>
  <source srcset="/hero.avif" type="image/avif" />
  <source srcset="/hero.webp" type="image/webp" />
  <img
    src="/hero.jpg"
    alt="Team reviewing a dashboard"
    width="1200"
    height="630"
    loading="eager"
    fetchpriority="high"
  />
</picture>

Note the width and height attributes. They are not optional. Without them the browser does not know how much space to reserve, the layout jumps when the image loads, and your Cumulative Layout Shift (CLS) score suffers. They describe the intrinsic aspect ratio, not the rendered size: CSS can still make the image fluid.

Serve the right size, not the original

A 4000px-wide image displayed in a 600px column is wasted bytes. You want the browser to download something close to the size it will actually render, accounting for the device pixel ratio. Lighthouse flags it in its image delivery audit, and it is one of the most common failures we see on inherited sites.

Responsive images solve this with srcset and sizes. You provide several widths and tell the browser how wide the image will be at different breakpoints, and it picks the smallest file that still looks sharp:

<img
  src="/photo-800.webp"
  srcset="/photo-400.webp 400w, /photo-800.webp 800w, /photo-1600.webp 1600w"
  sizes="(max-width: 768px) 100vw, 800px"
  alt="Product screenshot showing the order history table"
  width="800"
  height="600"
  loading="lazy"
  decoding="async"
/>

A phone around 400px wide on a 2x display, reading sizes of 100vw, needs roughly 800 device pixels and grabs the 800w file. A desktop showing the image at a fixed 800px also grabs 800w. Only a high-density desktop screen reaches for the 1600w version. You stop shipping desktop-sized images to phones.

How to get sizes right

sizes is where most responsive image setups quietly go wrong, because it is a promise you make to the browser before it has laid out the page. If you say 100vw for an image that renders in a third of the screen, you get files three times wider than needed. If you understate it, images look soft.

  1. Open the page at a few widths and check the rendered width of the image in DevTools.
  2. Write sizes to match your CSS layout at each breakpoint, from narrowest to widest.
  3. Add a fixed fallback at the end for the widest layout.
  4. Re-check after any layout change. A grid that goes from three columns to two changes the answer.

For fixed-size images such as avatars or logos, you do not need sizes at all: use x descriptors (1x, 2x) in srcset instead.

Lazy load everything below the fold

Images that are not visible on first paint should not compete with the ones that are. The native loading="lazy" attribute defers them until the user scrolls near them, and browser-level lazy loading is supported everywhere that matters. It costs one attribute per tag and needs no JavaScript library.

The important nuance: never lazy-load your LCP image. Lazy loading tells the browser to wait, which is the opposite of what you want for the one image that defines your LCP. Load the hero with loading="eager" and fetchpriority="high", and lazy-load the rest.

A few more loading rules we follow:

  • Make the hero discoverable in the HTML. A hero set as a CSS background, injected by JavaScript, or rendered after a client-side fetch is found late. Render it as a real img in server-rendered markup.
  • Do not lazy-load images that are near the top on mobile. A product image that is below the fold on desktop may be the first thing a phone shows.
  • Use decoding="async" on non-critical images so decoding does not hold up other rendering work.
  • Do not lazy-load with JavaScript if the native attribute will do. Script-based lazy loaders delay discovery and add main-thread work.

Let Next.js do the heavy lifting

If you are on Next.js, the next/image component handles most of this for you. It generates a responsive srcset, serves modern formats based on the browser's Accept header, lazy-loads by default, and reserves space to prevent layout shift. You mostly need to use it correctly.

import Image from "next/image";
import cover from "./optimization-cover.jpg";
 
export function ArticleHero() {
  return (
    <Image
      src={cover}
      alt="Network panel showing image transfer sizes"
      preload
      sizes="(max-width: 768px) 100vw, 1200px"
      placeholder="blur"
    />
  );
}

Three details matter here:

  • preload marks the LCP image. In Next.js 16 the old priority prop is deprecated in favour of preload, which inserts a preload link in the document head. The docs also note that in most cases loading="eager" or fetchPriority="high" is the better choice, and that you should not use preload when different images could be the LCP element at different viewport sizes. Use it on one image per page at most.
  • sizes makes the srcset useful. Without sizes, Next.js generates a limited 1x/2x set suited to fixed-size images, and the browser assumes a full-viewport width for anything responsive. With it, you get the full range of widths.
  • A static import gives you dimensions and a blur placeholder for free. Importing the file lets Next.js read its width and height, generate the blurDataURL, and hash the filename so it can be cached as immutable.

Configure next.config for remote images and formats

Remote images need their host allowed in next.config.ts, otherwise the optimizer refuses them. Since Next.js 16, the allowed quality values are also an explicit list (the default is [75]), and the output format defaults to WebP only:

import type { NextConfig } from "next";
 
const config: NextConfig = {
  images: {
    formats: ["image/avif", "image/webp"],
    qualities: [60, 75],
    remotePatterns: [
      { protocol: "https", hostname: "cdn.example-store.net" },
    ],
  },
};
 
export default config;

Two caveats are worth knowing. First, the built-in optimizer runs on your server, so a flood of unique image requests costs compute, and with multiple formats enabled each format is cached separately. Second, if you serve a lot of user-uploaded images, point a custom loader at a dedicated image CDN and let it transform and cache at the edge. If a proxy or CDN sits in front of a self-hosted Next.js app, make sure it forwards the Accept header, or every browser gets the fallback format.

Compress before you ship

Even after picking AVIF or WebP, the quality setting matters. For photographs, quality around 75 is a sensible starting point, and it is the Next.js default. Above roughly 85 you mostly add weight. Quality numbers are not comparable across codecs, so an AVIF at a lower number can look as good as a JPEG at a higher one. Compare outputs side by side (a tool like Squoosh makes this easy) rather than copying a number between formats.

For a build-time pipeline, sharp is the standard tool in the Node world and is fast because it wraps libvips. Its output options cover WebP, AVIF and the rest:

import sharp from "sharp";
 
await sharp("input.jpg")
  .resize({ width: 1600, withoutEnlargement: true })
  .rotate() // respect EXIF orientation before metadata is stripped
  .avif({ quality: 50 })
  .toFile("output.avif");

withoutEnlargement stops sharp from upscaling a small source into a bigger, blurrier, heavier file. Sharp also strips metadata such as EXIF by default, which saves bytes and avoids leaking camera or location data from uploaded photos.

Alt text, filenames and image SEO

Optimization is not only about bytes. Every meaningful image needs alt text that says what the image communicates in context, and decorative images need an empty alt="" so screen readers skip them. The W3C alt text decision tree is the quickest way to decide which is which, and it is a core part of our 80/20 guide to accessibility.

Good alt text also helps search. Google's image SEO guidance recommends real img elements (not CSS backgrounds) for important images, descriptive filenames, and alt text placed near relevant page content. A file called blue-linen-shirt-front.webp tells Google more than IMG_4821.webp.

Common image optimization mistakes

These are the issues we find most often when we audit an existing site:

MistakeWhat happensFix
loading="lazy" on the heroSlow LCPLoad eagerly with high fetch priority
sizes missing or set to 100vw everywherePhones download desktop-width filesMatch sizes to the real layout
Hero as a CSS background imageBrowser discovers it lateUse a real img element in the HTML
No width and heightLayout shift as images loadSet dimensions or aspect-ratio
Animated GIFsMegabytes for a short loopMuted, looping MP4 or WebM
Uploads served at original sizeMulti-megabyte product photosResize and convert on upload or via an image CDN
Upscaled small sourcesBlurry and heavy at oncewithoutEnlargement in your pipeline
A CMS that ignores all of the aboveEditors undo your work weeklyEnforce sizes and formats in the CMS pipeline

That last row matters more than it looks. If marketing uploads images through a CMS, the optimization has to live in the pipeline, not in a developer's head. It is one of the reasons we recommend the setup in our guide to headless CMS for marketing teams, and one of the first things we fix when moving a site from WordPress to Next.js.

Measure, fix the biggest file first, then keep it fast

Do not guess. Open DevTools, filter the network panel to images and sort by transfer size: the offenders announce themselves immediately. Then check three things:

  1. LCP: is your hero arriving fast? The DevTools Performance panel shows which element is the LCP and how long each phase took.
  2. CLS: is the page jumping as images load? The Layout Shift regions overlay points straight at the culprit.
  3. Total image weight: how many megabytes does a first visit actually download?

Fix the biggest file first, re-measure, repeat. Most sites get the bulk of their improvement from the top three or four images. Then confirm with field data from real users, because a fast laptop on office wifi tells you very little about a mid-range phone on a train.

You do not need an elaborate setup to get fast images. Serve WebP (and AVIF where the encode cost is paid once), size images to how they actually render with accurate sizes, set dimensions on everything, lazy-load all but the LCP image, and compress around quality 75. On Next.js, next/image gives you most of this for free as long as you set sizes correctly and mark the hero with preload or fetchPriority="high" instead of the deprecated priority.

If your pages are heavy and you want them fixed properly, including the CMS pipeline that keeps them fast, our performance and SEO engineering team does exactly this. Tell us about your site and we will tell you where the bytes are going.

Photo-heavy sites feel this most. Property portals are a good example, and we cover listings, images and map search in web platforms for real estate.

FAQ ยท 05 questions

Frequently asked questions

What is the best image format for websites in 2026?

WebP is the safest default for photos because every current browser supports it and it is much smaller than JPEG or PNG. AVIF usually compresses smaller still but is slower to encode, so it suits images that are encoded once and cached. Use SVG for logos and icons, and PNG only when you need lossless detail such as UI screenshots.

Should I lazy load all images?

No. Lazy-load images that are below the fold, but load the hero or any image likely to be the Largest Contentful Paint element eagerly and at high priority. Lazy-loading the LCP image tells the browser to wait, which is the single most common cause of a slow LCP we see.

What image quality setting should I use?

For photographs, a quality around 75 is a sensible starting point and is the default in Next.js. Above roughly 85 the files grow quickly with little visible gain. AVIF and WebP quality numbers are not equivalent to JPEG numbers, so compare outputs side by side rather than copying one number across formats.

Do image sizes affect SEO?

Indirectly, yes. Heavy images slow down Largest Contentful Paint, and Core Web Vitals are part of how Google evaluates page experience. Descriptive filenames, alt text and crawlable img elements also help your images appear in Google Images.

Why does my image look blurry after optimization?

Usually the browser picked a file that is too small because the sizes attribute understates how wide the image renders, or the source was upscaled. Check the rendered width in DevTools, correct sizes, and make sure your pipeline never enlarges an image beyond its original dimensions.

Related service

Performance & SEO Engineering

Top Core Web Vitals and search visibility, by design.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts