Skip to content

Compressing and Optimizing Images for a Faster Website

A practical guide to optimizing images: why images are the heaviest element, modern formats (WebP/AVIF) vs. JPEG/PNG, resizing and responsive images with srcset, compression with no visible loss, lazy loading, image dimensions to avoid CLS, delivery through a CDN, the tools, and the effect on LCP and Core Web Vitals.

Performance and speedمريم العتيبي26 min read
Illustration of a large picture compressed into a smaller lighter picture, representing image optimization for faster websites
On this page

This is a reference guide that works for any platform (a custom site, WordPress or a store), because the principles of image optimization are the same even if the tools differ. We will explain each step in depth with comparison tables and practical code, then close with a ready-made workflow, a checklist, common mistakes and frequently asked questions. For the bigger picture, also read the complete guide to speeding up your website, which puts images in the context of overall performance.

Why are images the heaviest element on the page?

On most sites, if you open the developer tools and sort network requests by size, you will find images at the top of the list, far ahead of HTML, CSS and even JavaScript. The reason is simple: a photo carries millions of pixels, and every pixel is a color. An unoptimized 2000×1333-pixel JPEG can easily exceed 2 megabytes, while a complete HTML page rarely goes beyond a few dozen kilobytes.

The impact of this weight does not stop at "the page is heavy." It is reflected directly in two of the Core Web Vitals:

  • LCP (Largest Contentful Paint): on most pages, the largest visible element is an image: the hero image, the article cover or the main product image. Unless this image loads quickly, LCP will remain poor however much you optimize the rest of the page. The official target is under 2.5 seconds.
  • CLS (Cumulative Layout Shift): an image without reserved dimensions suddenly pushes the content down when it arrives, so the layout jumps and CLS rises. The target is under 0.1.
Page weight: before and after optimizationImagesScriptsStyles/fontsBeforeCompressed imagesMinified assetsAfterCompressed images + reduced/deferred assets = a lighter, faster page
Page weight before/after: compressing images and reducing scripts and styles clearly shrinks the total size, improving load time.

Worse still, slowness has a direct business cost: the longer loading takes, the more likely the visitor is to leave before even engaging. This relationship between load time and bounce rate is well documented.

How does slowness raise the bounce rate?Bounce rateLoad time (seconds)1s3s5s7sEvery extra second of delay raises the chance of leaving
The relationship between load time and bounce rate: the longer loading takes, the more likely the visitor is to leave before engaging.

The good news is that images are also the biggest opportunity for improvement: saving 70% of an image's weight is far easier than saving 70% of your JavaScript, and it usually doesn't require touching the code. That makes optimizing images the first thing to start with in any speed project. To understand the metrics in detail, see understanding Core Web Vitals.

Core Web Vitals: page experience metricsCLSLayout stabilityGoodPoor< 0.1INPResponsivenessGoodPoor< 200 msLCPLargest elementGoodPoor< 2.5 secondsGreen = the good target · measured from real user data
Core Web Vitals: LCP (largest element appears) < 2.5 seconds, INP (responsiveness) < 200 ms, CLS (layout stability) < 0.1.

The image pipeline: from upload to browser

Before diving into the details, it helps to see the image's whole journey, from the moment the photographer or designer captures it until it appears in the visitor's browser. Every step in this pipeline is an opportunity to optimize, or to neglect.

Image optimization: from original to lightestOriginalLarge and heavyResizeProper srcsetCompressNo visible lossModern formatWebP / AVIFLazy loading + CDN deliveryEach step cuts weight — a lighter page and faster LCP
The image optimization pipeline: heavy original > proper resizing (srcset) > compression with no visible loss > modern format (WebP/AVIF) > lazy loading and CDN delivery.

The steps in order:

  1. Source: a high-resolution original file (PNG/JPEG/PSD), possibly several megabytes.
  2. Resize: reduce the dimensions to what the page actually needs, no more.
  3. Encode (choose the format): convert to AVIF/WebP with JPEG as a fallback.
  4. Compress: set the quality level to balance size and clarity.
  5. Generate multiple sizes: copies at different widths for srcset.
  6. Storage and delivery (CDN): upload to object storage and deliver from the nearest point.
  7. Display in the browser: with width/height, loading, decoding and sizes.

Any site that does not apply this pipeline pays twice: once in weight and once in experience. Let's go through each step in detail.

Step 1: choosing the right format

There is no absolute "best format"; each format has its ideal use. The general rule: AVIF, then WebP, for photos and complex graphics, SVG for icons and logos, and JPEG/PNG as a fallback only when needed.

Comparing the five main formats

FormatBest useSupportRelative sizeTransparencyAnimation
JPEGPhotos (fallback)Universal (100%)Baseline (100%)NoNo
PNGTransparency, sharp text, screenshotsUniversal (100%)Very large for photosYesNo
WebPA general replacement for JPEG/PNGExcellent (~97%)~25–35% smaller than JPEGYesYes
AVIFThe best compression for modern imagesGood (~93%)~50% smaller than JPEGYesYes
SVGIcons, logos, vector graphicsUniversal (100%)Very smallYesYes (CSS/SMIL)
JPEG vs. WebP vs. AVIF (file size)JPEGWebPAVIF≈ 100%≈ 70%≈ 50%Approximate ratios for the same image — the lightest loads fastest
The same image in three formats: WebP is clearly lighter than JPEG, and AVIF is the lightest, a big gain in page weight with no visible loss.

When should you choose each format?

ScenarioIdeal formatFallback
A photographic hero imageAVIFWebP → JPEG
An article cover / blog imageAVIFWebP → JPEG
A product image (fine details)AVIF at higher qualityWebP → JPEG
A logo, icon or vector chartSVGPNG
A screenshot with sharp textWebP (lossless)PNG
A graphic that needs sharp transparencyWebP/AVIFPNG
An old animated GIFWebP or MP4/WebM video—

Two important tips: first, animated GIFs are very bad for weight; replace them with a <video> in WebM/MP4 format or with animated AVIF/WebP, and the savings reach 90%. Second, don't use PNG for a photo; PNG is designed for lossless compression, so it produces a huge file for images with many color gradients. PNG is excellent for sharp text and transparency only.

As for the delivery mechanism, the simplest reliable way is the <picture> element, which serves AVIF first, then WebP, then JPEG for browsers that don't support the modern formats:

html
<picture>
  <source srcset="/images/hero.avif" type="image/avif" />
  <source srcset="/images/hero.webp" type="image/webp" />
  <img src="/images/hero.jpg" alt="Hosting control panel" width="1200" height="630" />
</picture>

The browser picks the first format it supports, from top to bottom, so users of modern browsers get the lighter AVIF, and everyone can still see the image. If you are on WordPress or a CDN that converts formats automatically, you probably won't write this by hand, but understanding the mechanism helps you diagnose problems.

Step 2: compression, lossy vs. lossless

There are fundamentally two kinds of compression, and mixing them up is one of the most common mistakes:

TypeThe ideaQualitySizeIdeal use
LosslessRemoves redundancy without deleting any pixel100% identical to the originalModerate reductionScreenshots, sharp text, logos
LossyDeletes details the eye can hardly tell apartSlight visual loss, controlled by the quality levelVery large reductionPhotos

For photos, lossy compression is almost always the right choice: the human eye cannot see the difference between the original and a copy compressed at quality 80, while the size drops to a third or less. The real question is: what quality level is right?

Quality vs. size: where do you set the dial?

Quality levelVisual perceptionRelative sizeRecommendation
95–100No noticeable difference; wastefulLargeAvoid it; waste with no benefit
82–90Excellent; safe for detailed productsMedium to largeFor product images and anything that gets zoomed
75–82Excellent to the eye; the ideal balanceMediumThe recommended default
60–74Good; some loss visible on close inspectionSmallFor secondary images and thumbnails
< 55Obvious artifactsVery smallAvoid it for important images

The golden rule: start at quality 80 and go down gradually until you see the first visual difference, then go up one step. This is the "visual quality threshold," and it varies slightly from image to image: images with flat areas of color (sky, a wall) tolerate more compression than images crowded with detail (leaves, textures).

Command-line tools give you precise control. To convert an image to WebP at quality 80 with the cwebp tool:

bash
# Lossy WebP at quality 80
cwebp -q 80 input.jpg -o output.webp

# Lossless WebP (for screenshots and sharp text)
cwebp -lossless input.png -o output.webp

And to generate AVIF with avifenc (from the libavif package):

bash
# Lossy AVIF: lower --min/--max = higher quality; speed 6 is a good balance
avifenc --min 24 --max 30 --speed 6 input.jpg output.avif

Step 3: resizing and responsive images (srcset)

The single biggest image mistake is uploading an image with huge dimensions and displaying it small. A 4000-pixel-wide image displayed in a 400-pixel-wide container wastes 90% of its data, and the browser is forced to download it in full and then scale it down. The solution has two parts: resize to what you need, and serve multiple sizes for different screens.

Common display dimensions

Image positionApproximate display widthSuggested srcset widths
A wide hero image (full-width)Up to 1920px640, 960, 1280, 1920
An article coverUp to 1200px480, 768, 1024, 1200
An in-body imageUp to 760px380, 560, 760
A card in a grid~360px360, 540, 720
Thumbnail~120px120, 240
Avatar~48px48, 96

Notice that each row includes a copy at double the width (such as 360 and 720): this covers high-density screens (DPR ≥ 2, such as Retina displays), which need more physical pixels for each CSS pixel.

How do srcset and sizes work together?

The srcset attribute tells the browser which copies are available and the width of each in pixels (with the w descriptor), and the sizes attribute tells it the width at which the image will actually be displayed at each breakpoint, so the browser picks the most suitable copy on its own based on the screen and its density:

html
<img
  src="/images/cover-768.jpg"
  srcset="
    /images/cover-480.jpg   480w,
    /images/cover-768.jpg   768w,
    /images/cover-1024.jpg 1024w,
    /images/cover-1200.jpg 1200w"
  sizes="(max-width: 600px) 100vw, (max-width: 1024px) 80vw, 1200px"
  width="1200" height="630"
  alt="Comparison of hosting plans"
  decoding="async"
/>

Read sizes like this: "On screens up to 600 pixels, display the image at the full viewport width (100vw); up to 1024 pixels, at 80% of the width; otherwise at 1200 pixels." With this information, the browser can calculate the smallest sufficient copy for each device. Without accurate sizes, you lose the benefit of srcset, because the browser assumes the image is full-screen width and picks a larger copy than needed.

A key point: don't write all of this by hand for every image. On WordPress, the system generates srcset/sizes automatically from the registered "image sizes," and in Next.js, next/image handles the generation entirely. Your job is to make sure the multiple copies are generated and that sizes reflects your real layout.

Step 4: lazy loading without hurting LCP

Lazy loading defers downloading images outside the screen's viewport until the user scrolls close to them, which speeds up the initial load and saves data on images the visitor may never reach. Enabling it has become simple with a native browser attribute:

html
<!-- An image lower down the page: lazy-load it -->
<img src="/images/section-3.webp" loading="lazy" decoding="async"
     width="800" height="450" alt="Statistics dashboard" />

But here is the most dangerous trap in the whole topic:

Never lazy-load the LCP image, that is, the first visible image above the fold, such as the hero image or the article cover. Lazy-loading it delays its download, so LCP gets much worse, which is the opposite of what you want.

The practical rule:

Image positionloadingfetchpriorityReason
The LCP image (hero/cover, above the fold)eager (the default)highLoad it immediately and with high priority
Above-the-fold images other than LCPeager—Visible immediately
All images below the foldlazy—Defer them until the user gets close

To speed up the LCP image specifically, add fetchpriority="high" to raise its priority in the download queue:

html
<!-- The hero / LCP image: load it early -->
<img src="/images/hero.avif" fetchpriority="high" decoding="async"
     width="1200" height="630" alt="Fast hosting" />

The decoding="async" attribute lets the browser decode the image without blocking the main thread; it is safe for most images and helps responsiveness.

An expert tip: on WordPress, the core adds loading="lazy" to all images automatically, sometimes including the LCP image. Make sure your theme or performance plugin excludes the first image (or gives it fetchpriority="high"). Many slow sites are slow because the hero image is lazy-loaded by mistake.

Step 5: setting width and height to avoid CLS

When the browser does not know an image's dimensions in advance, it reserves zero space for it and then suddenly pushes everything below it down when it arrives; this is the best-known cause of layout shift (CLS). The fix is very simple and often neglected: write the real width and height (in pixels) on every image, even if it is responsive.

html
<!-- Aspect ratio preserved: the browser reserves the space before the download -->
<img src="/images/chart.webp" width="800" height="450"
     style="height:auto" alt="Performance growth" loading="lazy" />

The secret is that modern browsers use width and height to calculate the aspect ratio, so they reserve a box of the right size before the image arrives. With style="height:auto" (or an equivalent CSS rule), the image stays responsive but its ratio is preserved, so nothing jumps. This is the cheapest optimization step of all: one line per image drops CLS to almost zero.

CaseEffect on CLS
An image without width/heightA severe jump when it arrives: high CLS
width/height + height:autoSpace reserved: CLS ≈ 0
A container with a CSS aspect ratio (aspect-ratio)An excellent alternative that also reserves the space

Step 6: delivery through a CDN and automatic format conversion

After compressing and resizing your images, one factor remains: distance. A visitor geographically far from your server waits longer for the image to arrive. This is where a content delivery network (CDN) comes in: it stores copies of your images at points of presence distributed around the world and serves each visitor from the nearest point. This noticeably cuts the image's arrival time (and therefore LCP) for an international audience.

Better still, modern image CDNs do more than delivery: they convert the format, resize and compress on demand based on the visitor's browser and screen size. You upload a single original image and request it with a URL carrying parameters, and the network returns the optimal copy:

text
# Example: an image CDN URL that resizes, converts and sets quality on demand
https://cdn.example.com/hero.jpg?width=768&format=auto&quality=80

format=auto means: "Give this visitor AVIF if their browser supports it, otherwise WebP, otherwise JPEG," automatically, without you generating the copies yourself. This simplifies the workflow a lot. For a deeper understanding of how a CDN works and its security and performance benefits, see what a CDN is and why you need one.

If you serve WebP manually from your server without a CDN, you can configure Nginx to serve a WebP copy automatically to supporting browsers based on the Accept header:

nginx
# Serves x.webp instead of x.jpg if the browser supports webp and the copy exists
location ~* \.(jpe?g|png)$ {
    add_header Vary Accept;
    try_files $uri$webp_suffix $uri =404;
}

map $http_accept $webp_suffix {
    default        "";
    "~*image/webp" ".webp";
}

Tools: from manual to online to plugins

You don't need every tool; you need the right tool for your context. Here is a practical map:

Compression and conversion tools

ToolTypeFeaturesBest for
SquooshOnline (free)Live before/after comparison, AVIF/WebP, fine controlIndividual images, learning the thresholds
TinyPNGOnline (free/paid)Smart PNG/JPEG/WebP compression, APIQuick batches
cwebp / avifencCommand lineFull control, automation, huge batchesDevelopers and CI
ShortPixelPlugin/online/APIAutomatic AVIF/WebP conversion, optional CDNWordPress and live sites
ImagifyPlugin/online/APIAutomatic compression at different levels, WebP/AVIFWordPress
SharpA Node.js libraryThe fastest programmatic processing, srcset generationBuilds and pipelines

WordPress image plugins

PluginCore functionNote
ShortPixelCompression + WebP/AVIF conversion + CDNComprehensive and easy
ImagifyCompression at different levels + WebP/AVIFFrom the makers of WP Rocket
EWWW Image OptimizerLocal/cloud compression + WebPWorks without a subscription for the basics
SmushCompression + lazy loading + resizingA simple interface
Converter for MediaConverting and serving WebP/AVIFSpecialized in conversion

A tip: don't combine more than one compression plugin; they may conflict and compress the image twice, ruining it. Choose one and configure it well. And for more on speeding up WordPress as a whole, see speeding up a WordPress site.

A ready-made practical workflow

For a custom site (manual or build)

  1. Start from the highest-resolution original you will need (for example, 1920px for the hero).
  2. Resize to each width in your srcset plan (for example, 640/960/1280/1920).
  3. Convert each width to AVIF and WebP (and keep JPEG as a fallback).
  4. Compress at quality 80 (lower for secondary images, higher for products).
  5. Display through <picture> or srcset/sizes with width/height.
  6. Lazy-load what is below the fold, and prioritize the LCP image with fetchpriority="high".
  7. Deliver through an image CDN with format=auto.

A simple Node script using the Sharp library generates all the copies in one go:

js
import sharp from "sharp";

const widths = [640, 960, 1280, 1920];
for (const w of widths) {
  await sharp("hero.jpg").resize(w)
    .avif({ quality: 50 }).toFile(`hero-${w}.avif`);
  await sharp("hero.jpg").resize(w)
    .webp({ quality: 80 }).toFile(`hero-${w}.webp`);
}

For a WordPress site

  1. Install one compression/conversion plugin (ShortPixel or Imagify) and enable WebP/AVIF.
  2. Enable "resize large images on upload" (WordPress does this by default above 2560px, and you can lower it).
  3. Compress the existing media library in one go (Bulk).
  4. Make sure the theme outputs width/height and srcset (modern themes do).
  5. Exclude the hero/cover image from lazy loading, and give it high priority.
  6. Enable a CDN (through the plugin or your provider).

Measuring: how do you know you have succeeded?

Optimization without measurement is guesswork. Use these tools:

ToolMeasuresWhen to use it
PageSpeed InsightsField + lab LCP/CLS + image recommendationsA full check and "next-gen formats" recommendations
Lighthouse (DevTools)A detailed local audit of imagesDuring development and diagnosis
DevTools > NetworkThe actual size and timing of each imageFinding the heaviest images quickly
WebPageTestA precise loading waterfall + prioritiesAdvanced LCP diagnosis

The fastest manual check: open DevTools > the Network tab > sort by Size descending > reload the page. The heaviest rows are your first targets. And in Lighthouse, watch for two recurring recommendations: "Serve images in next-gen formats" (that is, convert to WebP/AVIF) and **"Properly size images"** (that is, you are serving larger dimensions than are displayed).

Common mistakes and how to avoid them

MistakeImpactCorrection
Uploading images with huge dimensions and displaying them smallEnormous wasted weight and a slow LCPResize to the displayed dimensions + srcset
Using PNG for photosFiles 5–10 times largerUse JPEG/WebP/AVIF
Lazy-loading the LCP image (hero/cover)A sharp drop in LCPeager + fetchpriority="high" for the first image
Missing width/heightLayout jumps and a high CLSAdd both + height:auto
Quality 95–100 for no reasonDouble the size with no visual benefitSet it to 75–82
A heavy animated GIFTens of megabytesReplace it with <video> or WebP/AVIF
Neglecting alt textHarms accessibility and image SEOWrite descriptive alt text for every content image
Double compression by more than one pluginDistorted, corrupted imagesOnly one compression plugin
Forgetting a CDN for an international audienceA slow LCP for distant visitorsAn image CDN with format=auto

The accessibility point deserves emphasis: alt text is not a luxury. It is what a screen reader reads aloud to a blind user, what the search engine relies on to understand the image, and what appears if the image fails to load. Write it descriptively and accurately for content images, and leave it empty (alt="") only for purely decorative images, so screen readers skip them.

A quick image optimization checklist

ItemDone?
All photos are in AVIF/WebP with a fallback☐
Icons and logos are in SVG☐
No image is larger than its actual display dimensions☐
srcset + sizes for every responsive image☐
Quality set to 75–82 (not 95+)☐
width + height + height:auto on every image☐
Below-the-fold images use loading="lazy"☐
The LCP image is not lazy-loaded + fetchpriority="high"☐
decoding="async" on images☐
Delivery through an image CDN with format=auto☐
Descriptive alt text for every content image☐
Before/after measurement with PageSpeed/Lighthouse☐

Troubleshooting

SymptomLikely causeFix
Slow LCP despite compressed imagesThe LCP image is lazy-loaded or low priorityRemove lazy and add fetchpriority="high"
High CLS when images loadMissing width/heightAdd the dimensions + height:auto
WebP/AVIF doesn't show for some visitorsNo fallback, or a missing Vary headerUse <picture> or add Vary: Accept
Images look distorted (artifacts)Compression quality is too lowRaise the quality above 70
Images are still heavy after installing the pluginThe original dimensions are hugeEnable resizing on upload
srcset saves nothingsizes is inaccurate or missingSet sizes to match the actual layout
An image is not served from the CDNThe cache hasn't warmed up, or the URL is the originCheck the cf-cache-status/x-cache header
WordPress serves the large original copyThe theme doesn't support srcset, or the sizes were deletedRegenerate the sizes (Regenerate Thumbnails)

Frequently asked questions

What is the difference between WebP and AVIF, and which should I choose? Both are modern formats with excellent compression and support for transparency and animation. AVIF produces smaller files (up to 50% smaller than JPEG), but its support is slightly narrower and its encoding is slower. WebP has wider support (~97% of browsers), encodes faster and is 25–35% lighter than JPEG. The best approach: serve AVIF first, then WebP, then JPEG through <picture> or a CDN with format=auto, so every visitor gets the best option available to them.

Can I drop JPEG and PNG entirely? Not yet. Keep JPEG as a fallback for the small share of old browsers, and keep PNG for screenshots, sharp text and critical transparency where lossless compression is required. But don't use them as the default format for photos; AVIF/WebP are lighter.

What is the ideal quality level for compression? For photos, 75 to 82 is an ideal balance between clarity and size that hardly anyone can tell apart by eye. Raise it to 85–90 for product images that get zoomed in, and lower it to 60–70 for secondary images and thumbnails. Avoid 95+, which is wasteful, and avoid anything below 55, which shows artifacts.

What is lazy loading, and when should I not use it? Lazy loading (loading="lazy") defers downloading off-screen images until the user scrolls close to them, which speeds up the initial load. Never use it for the LCP image (the hero/cover above the fold); lazy-loading it delays the appearance of the largest element, so LCP gets worse. Lazy-load only what is below the fold.

How do images raise CLS, and how do I prevent it? When an image arrives without reserved dimensions, it suddenly pushes the content below it, so the layout jumps (CLS). Prevent this by writing the real width and height on every image along with style="height:auto"; the browser then reserves the right space based on the aspect ratio before the image arrives. Another option: set an aspect-ratio for the container in CSS.

What is the right image size for the web? There is no single number; it depends on where the image is displayed: an optimized article cover is usually 50–150 KB, an in-body image smaller, and an optimized hero image may reach 150–250 KB. The rule: resize to the display dimensions, convert to AVIF/WebP, and set the quality to 80, and you will reach these numbers automatically. Any content image over half a megabyte is usually not optimized.

Does next/image optimize images automatically? Yes. The next/image component generates srcset/sizes, converts to AVIF/WebP, adds width/height to prevent CLS, and lazy-loads what is below the fold automatically. Your job is to pass the correct dimensions and to set priority on the LCP image to load it early (equivalent to fetchpriority="high" and disabling lazy loading).

What should I do with animated GIFs? Replace them. GIF is an old, very heavy format (sometimes tens of megabytes). Convert them to a <video> in WebM/MP4 format (with autoplay muted loop playsinline) or to animated AVIF/WebP; the savings reach 90% of the weight, with better quality.

Is using a CDN enough without compressing images? No. A CDN brings the image geographically closer, but it does not fix a 3 MB image; it stays heavy, just closer. The right order: compress and resize first, then deliver through a CDN. Best of all is an image CDN that converts and resizes on demand, combining both. See What is a CDN for details.

How do I actually measure the improvement from optimizing images? Run PageSpeed Insights and watch LCP and the "next-gen formats" and "properly size images" recommendations, or open DevTools > Network and sort by size to see the heaviest images before and after. Compare LCP and CLS before and after optimizing; the improvement should be noticeable in both numbers.

Does optimizing images help SEO? Yes, in two ways: directly, by improving Core Web Vitals (a ranking signal in page experience), and indirectly, through descriptive alt text and meaningful file names that help the search engine understand the image and index it in image search. A faster site is also crawled more deeply and keeps visitors longer.

Conclusion

Images are the heaviest element on most pages, and therefore the biggest opportunity to speed them up. The recipe is clear and layered: a modern format (AVIF, then WebP), resizing to the actual dimensions, compression at quality 80, multiple sizes through srcset/sizes, lazy loading for what is below the fold while not lazy-loading the LCP image, reserved dimensions with width/height to prevent CLS, and delivery through a CDN with automatic conversion. Apply these steps and you will see page weight drop by 50–80% and Core Web Vitals improve right away.

Most importantly, server performance complements all this effort; light images on a slow server still fall short. Start optimizing your images today, make sure your hosting is not the bottleneck, and measure the result.

Sources

Frequently asked questions

What is the difference between WebP and AVIF, and which should I choose?

Both are modern formats with excellent compression and support for transparency and animation. AVIF produces smaller files (up to 50% smaller than JPEG), but its support is slightly narrower and its encoding is slower. WebP has wider support (~97% of browsers), encodes faster and is 25–35% lighter than JPEG. The best approach: serve AVIF first, then WebP, then JPEG through <picture> or a CDN with format=auto, so every visitor gets the best option available to them.

Can I drop JPEG and PNG entirely?

Not yet. Keep JPEG as a fallback for the small share of old browsers, and keep PNG for screenshots, sharp text and critical transparency where lossless compression is required. But don't use them as the default format for photos; AVIF/WebP are lighter.

What is the ideal quality level for compression?

For photos, 75 to 82 is an ideal balance between clarity and size that hardly anyone can tell apart by eye. Raise it to 85–90 for product images that get zoomed in, and lower it to 60–70 for secondary images and thumbnails. Avoid 95+, which is wasteful, and avoid anything below 55, which shows artifacts.

What is lazy loading, and when should I not use it?

Lazy loading (loading="lazy") defers downloading off-screen images until the user scrolls close to them, which speeds up the initial load. Never use it for the LCP image (the hero/cover above the fold); lazy-loading it delays the appearance of the largest element, so LCP gets worse. Lazy-load only what is below the fold.

How do images raise CLS, and how do I prevent it?

When an image arrives without reserved dimensions, it suddenly pushes the content below it, so the layout jumps (CLS). Prevent this by writing the real width and height on every image along with style="height:auto"; the browser then reserves the right space based on the aspect ratio before the image arrives. Another option: set an aspect-ratio for the container in CSS.

What is the right image size for the web?

There is no single number; it depends on where the image is displayed: an optimized article cover is usually 50–150 KB, an in-body image smaller, and an optimized hero image may reach 150–250 KB. The rule: resize to the display dimensions, convert to AVIF/WebP, and set the quality to 80, and you will reach these numbers automatically. Any content image over half a megabyte is usually not optimized.

Does next/image optimize images automatically?

Yes. The next/image component generates srcset/sizes, converts to AVIF/WebP, adds width/height to prevent CLS, and lazy-loads what is below the fold automatically. Your job is to pass the correct dimensions and to set priority on the LCP image to load it early (equivalent to fetchpriority="high" and disabling lazy loading).

What should I do with animated GIFs?

Replace them. GIF is an old, very heavy format (sometimes tens of megabytes). Convert them to a <video> in WebM/MP4 format (with autoplay muted loop playsinline) or to animated AVIF/WebP; the savings reach 90% of the weight, with better quality.

Is using a CDN enough without compressing images?

No. A CDN brings the image geographically closer, but it does not fix a 3 MB image; it stays heavy, just closer. The right order: compress and resize first, then deliver through a CDN. Best of all is an image CDN that converts and resizes on demand, combining both. See What is a CDN for details.

How do I actually measure the improvement from optimizing images?

Run PageSpeed Insights and watch LCP and the "Serve images in next-gen formats" and "Properly size images" recommendations, or open DevTools > Network and sort by size to see the heaviest images before and after. Compare LCP and CLS before and after optimizing; the improvement should be noticeable in both numbers.

Does optimizing images help SEO?

Yes, in two ways: directly, by improving Core Web Vitals (a ranking signal in page experience), and indirectly, through descriptive alt text and meaningful file names that help the search engine understand the image and index it in image search. A faster site is also crawled more deeply and keeps visitors longer.