Performance··15 min read

Image Optimization: WebP, AVIF, and Lazy Loading

Speed up your site with image optimization: learn WebP, AVIF, lazy loading, and image compression techniques step by step with practical examples.

When a web page loads, the bulk of the data that gets downloaded is usually not text but images. High-resolution photos, product showcases, background pictures, and decorative icons add up to carry a significant portion of a page's total weight all on their own. That is precisely why image optimization ranks among the most effective and fastest-paying improvements you can make to speed up a site. Done correctly, it can cut page size in half, or even more, and you can achieve that without any visible loss in quality.

The problem is that many sites still serve enormous JPEG and PNG files exactly as they are, clinging to habits from a decade ago. Yet modern browsers now support far more efficient image formats, and the techniques for loading images only when they are actually needed have become standard. In this guide, we will dig deep into the modern formats that make your images lighter, the right compression strategies, and the lazy loading technique that dramatically accelerates page rendering.

Our goal is not to stay in the realm of theory; in every section you will find concrete steps you can apply, code examples, and practical criteria to help you make decisions. Whether you run a personal blog or a large e-commerce site, you can adapt the approaches here to your own project.

Why Is Image Optimization So Important?

When a user clicks on your page, the time they are willing to wait is far shorter than you might think. If the page does not show meaningful content within a few seconds, the visitor hits the back button. Images play a critical role in this equation because they are both the elements that take the longest to download and the ones that occupy the most space on screen.

The benefits of image optimization are not limited to a single area. The most concrete advantages can be listed as follows:

  • Faster page rendering: Smaller files download faster, so the user sees the content sooner.
  • Better user experience: Sudden layout shifts during loading and late-arriving images are reduced.
  • Search engine advantage: Page speed and Core Web Vitals metrics are direct signals that affect ranking.
  • Lower data cost: Users on mobile connections spend less data, which matters especially on limited plans.
  • Server and bandwidth savings: Less data traffic also lowers your hosting costs.

LCP (Largest Contentful Paint), which is part of Core Web Vitals, typically measures when the largest image on the page is painted. In other words, whether your page feels "loaded" largely depends on how quickly your biggest image arrives. The most direct way to improve this metric is to shrink that image and serve it correctly.

Performance Is Not Just Speed

Viewing image optimization solely as "saving seconds" is an incomplete perspective. Unoptimized images cause text and buttons to jump around while the page is loading. Just as the user is about to click a link, the arriving image shifts the layout and they click in the wrong place. That is both annoying and erodes trust. Proper sizing and space-reservation techniques prevent these problems.

Getting to Know the Image Formats: JPEG, PNG, WebP, and AVIF

Choosing the right format is the cornerstone of image optimization. Each format has its strengths and weaknesses; the right choice depends on the type of image and its intended use.

JPEG is a lossy format that has been used for photographs for decades. It compresses broad color gradients well but does not support transparency, and at the same quality it produces larger files than modern formats.

PNG offers lossless compression and supports transparency. It is ideal for logos, icons, and graphics with sharp edges; however, file sizes balloon for photographs.

WebP combines lossy and lossless compression, transparency, and animation into a single format. At the same visual quality, it produces noticeably smaller files than JPEG, and today it is supported by virtually all current browsers.

AVIF is a newer-generation format and generally provides even better compression than WebP. It stands out particularly for preserving quality at low file sizes, and it has additional advantages such as wide color depth and HDR support. In return, its encoding is slower and support in older browsers is not as widespread as WebP's.

Format Comparison Table

Feature JPEG PNG WebP AVIF
Compression type Lossy Lossless Lossy + lossless Lossy + lossless
Transparency (alpha) No Yes Yes Yes
Animation No No Yes Yes
Typical file size Large Very large Small Smallest
Browser support Full Full Very broad Broad (growing)
Encoding speed Fast Fast Medium Slow

As you read this table, keep this practical rule in mind: for photo-heavy images, AVIF and WebP are the best choices; for small elements with sharp edges that require transparency, WebP still delivers serious savings compared to PNG. In a modern workflow you generally set up AVIF as the first choice, WebP as the fallback, and JPEG/PNG as the final safe harbor.

How Do You Switch to WebP and AVIF?

Moving to the new formats does not mean "deleting all your images and reshooting them." You can start by converting your existing JPEG and PNG files. The key is to serve the most efficient format to modern browsers while leaving a fallback for older ones.

Image Compression and Conversion Tools

Graphical tools are practical for converting images one by one, but if you have hundreds of images, command-line tools are far more efficient. With open-source tools like cwebp, avifenc, and ImageMagick, you can perform batch conversions. For example, to convert an image to WebP:

cwebp -q 80 input.jpg -o output.webp

Here -q 80 specifies the quality level. To produce AVIF:

avifenc --min 24 --max 30 input.jpg output.avif

For batch conversion, you can write a script to process an entire folder in one go. This is the most robust way to automate the image compression process, and it eliminates human error.

Serving Multiple Formats with the picture Element

To let the browser automatically pick the best format it supports, you can use HTML's <picture> element. The browser evaluates the sources from top to bottom and loads the first format it supports:

<picture>
  <source srcset="product.avif" type="image/avif" />
  <source srcset="product.webp" type="image/webp" />
  <img src="product.jpg" alt="Blue ceramic mug" width="800" height="600" />
</picture>

In this structure, a browser that supports AVIF takes the AVIF, one that supports only WebP takes the WebP, and one that supports neither takes the JPEG at the bottom. Always specify the width and height values; this way the browser reserves space before the image downloads and prevents layout shift.

Correct Sizing and Responsive Images

One of the common mistakes in image optimization is shrinking a giant image with CSS to display it small on screen. The browser still downloads the large file; you are merely squeezing it visually. The correct approach is to serve the image at the size it will be used.

To send images at different sizes for different screen widths, use the srcset and sizes attributes:

<img
  src="banner-800.webp"
  srcset="banner-400.webp 400w, banner-800.webp 800w, banner-1600.webp 1600w"
  sizes="(max-width: 600px) 400px, (max-width: 1200px) 800px, 1600px"
  alt="Seasonal campaign poster"
  width="1600"
  height="900"
/>

Here the browser looks at the user's screen width and pixel density to select the most appropriate image. Instead of sending the 1600-pixel monster to a mobile user, you deliver the 400-pixel version. This is especially valuable for saving mobile data.

Retina and High Pixel-Density Screens

For images to look sharp on high pixel-density screens, you need a source roughly twice the physical pixel count. You can manage this situation with srcset as well. Even so, do not overdo it; doubling the file size for a sharpness the eye cannot distinguish contradicts your optimization goal. In practice, a 2x version is sufficient in most cases.

Lazy Loading: Load Images Only When Needed

Lazy loading means deferring the loading of images that are not yet visible on screen until the user approaches that section. A long page may contain dozens of images; however, the user may never see the image at the very bottom of the page. Downloading that image up front is a waste of both bandwidth and time.

The Browser's Built-In Lazy Loading Feature

The simplest and safest method is HTML's built-in loading attribute:

<img src="gallery-12.webp" alt="Workshop session" width="600" height="400" loading="lazy" />

When you add loading="lazy", the browser does not download the image until it gets close to the screen. This attribute has broad browser support today and requires no JavaScript. It is simple and effective.

Which Images Should You Not Lazy Load?

There is a critical point here: you should not lazy load images that are visible on screen when the page first opens (especially the LCP image, that is, the largest main image). Otherwise the browser delays that image and your LCP metric worsens. The rule is simple:

  1. The main image visible in the first viewport (above the fold): no lazy loading, and in fact give it priority.
  2. Images further down the page: deferred with loading="lazy".
  3. If there is a very critical hero image, you can bring it forward with fetchpriority="high".

Blindly applying lazy loading to every image without making this distinction can worsen performance rather than improve it.

JavaScript-Based Solutions and Placeholders

In situations where browser support falls short or where you want more advanced behavior, solutions using the Intersection Observer API come into play. With this method, you load the real source when the image enters the visible area. In addition, you can show a small blurred placeholder (the blur-up technique) or a solid color until the image arrives. This gives the user a positive sense that "something is loading" and reduces the anxiety of empty space.

Preventing Layout Shift

A frequently overlooked but very critical dimension of image optimization for user experience is that images should not disrupt the page layout. The Cumulative Layout Shift (CLS) metric measures how much elements move while the page is loading.

The most robust way to prevent this is to give every image width and height attributes or to specify aspect-ratio with CSS. With this information, the browser reserves the correct amount of space before the image downloads. When the image arrives, the content does not shift. In modern CSS, the following approach is very useful:

img {
  max-width: 100%;
  height: auto;
}

This rule lets the image behave responsively while preserving its proportions. Combined with the width and height attributes, you get a structure that is both flexible and prevents shifting.

Automatic Optimization and Integration into Your Workflow

Performing image optimization by hand for every new image is not sustainable. The best approach is to turn it into an automated process. There are several ways to do this.

Optimization at Build Time

Many modern site-building tools automatically optimize images during the build; they convert them to suitable formats, produce different sizes, and place the correct attributes. In this approach, it is enough to put the image in the source folder; the tool handles the rest. This is the method that contains the fewest errors and is the most scalable.

Image CDNs and On-the-Fly Conversion

Another approach is to use a content delivery network (CDN) that converts images on demand. With these services, you can request width, quality, and format by adding parameters to the URL; the CDN then produces and caches AVIF or WebP based on the browser's support. For high-traffic, image-heavy sites, this significantly improves both performance and ease of maintenance.

Manual Checklist

If you do not have a fully automated workflow, you can apply the following checklist for each image:

  1. Resize the image to the largest size at which it will be used.
  2. Convert it to a suitable format (preferably AVIF or WebP) and leave a fallback.
  3. Lower the quality level as far as possible without degrading visual quality.
  4. Write a descriptive alt text.
  5. Add loading="lazy" to images that are not in the first viewport.
  6. Specify the width and height values.

Once you make these six steps a habit, your site's image performance stays permanently high.

Images from an SEO and Accessibility Perspective

Image optimization is not only about file size; for search engines and accessibility, images also need to be correctly described. Write an alt text for every meaningful image that genuinely describes its content. This text is read by screen readers for users who cannot see the image, and it helps search engines understand the image. For purely decorative images, leaving the alt attribute empty (alt="") is the right choice; this way screen readers skip them.

Keep your file names meaningful too. Using a descriptive name like blue-ceramic-mug.webp instead of IMG_8842.jpg is beneficial for both organization and search visibility. Furthermore, on sites that host many large images, creating an image sitemap makes it easier for search engines to discover your images.

Common Mistakes

There are pitfalls that even experienced teams sometimes fall into. Being aware of them protects you from unnecessary performance losses:

  • Over-compression: Lowering quality too much saves bandwidth but makes images look blurry and full of artifacts. Balance matters.
  • One size for everyone: Sending a single giant image to all screens penalizes the mobile user.
  • Lazy loading the LCP image: Delaying the most important image distorts the very metric you are measuring.
  • Not specifying dimensions: Without width and height, the layout shifts.
  • Forgetting the format fallback: Serving AVIF alone without leaving a fallback can cause image loss in older browsers.
  • Using animated GIFs: Instead of large GIFs, a short video or animated WebP/AVIF is far lighter.

Reviewing these mistakes and checking for them on your own site often delivers noticeable speed gains with just a few hours of work.

Frequently Asked Questions

Should I use WebP or AVIF?

The ideal approach is to serve both. With the <picture> element, define AVIF first, then WebP, and finally the JPEG/PNG fallback last. This way every browser receives the most efficient format it supports. AVIF generally produces smaller files, but WebP has broader support and faster encoding. Using the two together guarantees both the best performance and the widest compatibility.

Does lazy loading hurt SEO?

No, when applied correctly it does no harm; on the contrary, it contributes to SEO by improving page speed. What matters is not lazy loading the critical images visible in the first viewport and ensuring search engines can still discover the images. HTML's built-in loading="lazy" attribute is safe in this regard, and modern search engines process it without any problems.

How much does image compression reduce quality?

This depends entirely on the quality setting you choose. With lossy compression, a quality value between 75 and 85 generally reduces file size significantly with a loss too small to notice with the naked eye. When you drop to very aggressive values, distortions become visible in color gradients. The best method is to experiment with several different quality values and compare them visually. The ideal value can differ for photos versus graphics.

Should I convert all my images to WebP?

In most cases, yes, but do it wisely. Photos and large images benefit most from WebP or AVIF. For very small icons, SVG is usually a more sensible choice, because its vector structure keeps it sharp at every size and it is generally smaller. So make the format decision based on the type of image; do not force a single format on everything.

Do I really need to add width and height to my images?

Yes, this is a strong recommendation. Thanks to the width and height attributes, the browser knows the space to be reserved for the image before it downloads, and the content does not shift while the page loads. This improves the Cumulative Layout Shift metric and visibly enhances the user experience. It does not conflict with responsive design; when used together with the height: auto rule in CSS, the image both preserves its proportions and stabilizes the layout.

How do I optimize my animated GIFs?

Animated GIFs are usually very large files and are extremely inefficient compared to modern alternatives. The best solution is to convert them to a short video format or an animated WebP/AVIF file. This conversion often reduces file size dramatically and delivers the same visual effect with far less data. For short auto-playing videos, prefer muted and looping settings.

Conclusion

Image optimization is one of those rare techniques that delivers a big payoff for relatively little effort. Choosing the right format, serving images at the size they will be used, applying modern compression, and loading images only when needed; when these four core principles come together, your site's speed, user experience, and search visibility all improve in tandem.

Start with your largest and most frequently viewed images, because they deliver the highest return. Serve AVIF and WebP together with a fallback, apply lazy loading to images outside the first viewport, and add dimension information and a meaningful alt text to every image. Automate this process wherever possible so that quality stays consistent.

Remember: performance is not a one-time job but a habit that requires ongoing maintenance. Every time you add a new image, you can keep your site light, fast, and user-friendly by applying the checklist in this guide. The small steps you take today will turn into a smoother experience for your visitors and a stronger digital presence for you.

Tags

image optimizationwebplazy loadingimage compression

Professional help for your web project

Want a website that is fast, mobile-friendly and SEO-ready? Let's talk about your idea.

Get in touch