Image Optimization on the Web: Formats, Sizing, and Lazy Loading

Matt George

Fractional CTO · Founder of Injuria.ai

Images are consistently the largest contributors to page weight on the web.[22] An effective image optimization strategy is not a micro-optimization; it is a foundational requirement for building fast, cost-effective, and user-friendly web applications.[23] Getting it right directly improves loading performance, reduces bounce rates, and lowers bandwidth costs for both the provider and the user. A complete strategy rests on three pillars: choosing the right format, serving the right size for the user's device, and loading the image at the right time.

This article provides a technical foundation for making informed decisions about each of these pillars. It covers the mechanisms behind image compression, the history and tradeoffs of various formats, the implementation of responsive images using standard HTML, and the correct application of modern loading techniques. The goal is to equip engineers and technical leaders with the knowledge to build a robust and automated image delivery pipeline.

Understanding Image Data and Compression

At its core, a digital image is a grid of pixels, with each pixel's color defined by a set of numbers. For a standard 24-bit color image, each pixel requires 3 bytes of data to represent its Red, Green, and Blue (RGB) values. An uncompressed 1024x768 image would thus require 1024 * 768 * 3 = 2.36 MB of data, a size far too large for efficient web delivery. Image compression algorithms are essential for reducing this file size.

Compression techniques fall into two broad categories: lossless and lossy.

Lossless compression reduces file size without discarding any information. When the image is decompressed, it is a perfect, bit-for-bit reconstruction of the original. This is achieved by finding and efficiently encoding statistical redundancies in the data, similar to how a ZIP file works. Formats like PNG and GIF use lossless compression, making them ideal for computer-generated graphics, logos, and diagrams where sharp lines and exact color fidelity are critical.

Lossy compression achieves much higher compression ratios by permanently discarding data that the human visual system is less likely to notice. This is the preferred method for photographic content. The key insight behind most lossy compression is that the human eye is more sensitive to changes in brightness (luma) than it is to changes in color (chroma). This allows for a technique called chroma subsampling[1], where color information is stored at a lower resolution than brightness information. A 4:2:0 subsampling scheme, common in JPEGs and video codecs, can reduce the data needed for color by 75% with little perceptual impact.

A Tour of Web Image Formats

The choice of image format is a fundamental decision that balances quality, file size, and browser compatibility.

The Classics: JPEG, GIF, and PNG

These three formats dominated the web for decades and remain important as universal fallbacks.

GIF (Graphics Interchange Format): First released by CompuServe in 1987[2], GIF was designed for slow connections. Its key features are a limited palette of 256 colors per frame, lossless compression using the Lempel-Ziv-Welch (LZW)[3] algorithm, and support for simple animations. Its transparency is binary: a pixel is either fully transparent or fully opaque. While its early history was complicated by patent disputes over LZW, it is now free to use. Today, its primary use is for simple, looping animations where modern video formats would be overkill, though its large file sizes and limited color depth make it a poor choice for most other tasks.

JPEG (Joint Photographic Experts Group): This format was standardized in 1992 (ISO/IEC 10918-1)[4] and became the standard for photographic images on the web. Its lossy compression algorithm is based on the Discrete Cosine Transform (DCT)[5]. The image is broken into 8x8 pixel blocks, and the DCT converts each block from spatial pixel values into a set of frequency coefficients. A process called quantization then aggressively compresses the high-frequency coefficients, which represent fine details the eye is less sensitive to. This is where the "quality" setting has its effect; a lower quality setting uses a more aggressive quantization matrix, discarding more data and resulting in a smaller file. JPEG does not support transparency.

PNG (Portable Network Graphics): Developed as an open, patent-free alternative to GIF, PNG was standardized as a W3C Recommendation in 1996[6]. It uses lossless compression based on the DEFLATE algorithm (RFC 1951)[7]. Unlike GIF, PNG supports 24-bit true color and an 8-bit alpha channel, which allows for multi-level, smooth transparency.[24] These features make it the superior choice for graphics, logos, icons, and any image requiring transparency or perfect line fidelity. Using PNG for photographs is generally a bad practice, as the lossless compression results in files that are significantly larger than a visually equivalent JPEG.

The Modern Contenders: WebP, AVIF, and JPEG XL

Modern formats offer superior compression by borrowing techniques from advanced video codecs.

WebP: Announced by Google in 2010[8], WebP provides both lossy and lossless compression in a single format. Lossy WebP is based on the intra-frame prediction techniques of the VP8 video codec (RFC 6386)[9], while lossless WebP uses different methods to achieve smaller file sizes than PNG. WebP also supports animation and alpha transparency. At equivalent visual quality, lossy WebP files are typically 25 to 34 percent smaller than JPEGs.[25] With near-universal support in modern browsers (96.8% of global users[10]), WebP is a safe and effective choice for improving performance over legacy formats.

AVIF (AV1 Image File Format): Derived from the powerful AV1 video codec[11], AVIF represents a major leap in compression efficiency. The AV1 codec was developed by the Alliance for Open Media[12], a consortium founded in 2015 that includes Google, Mozilla, Microsoft, Apple, and Amazon. AVIF routinely produces files that are 50% smaller than JPEG at a similar perceptual quality. It supports 10-bit and 12-bit color depth, high dynamic range (HDR), and both lossy and lossless compression. The primary tradeoff is encoding time; generating an AVIF is significantly more CPU-intensive than creating a JPEG or WebP. This makes it ideal for assets that are encoded once and served many times. As of late 2026, global support for AVIF is over 95%[13].

JPEG XL: Positioned as a true successor to JPEG, JPEG XL offers a rich feature set. Its most compelling feature is the ability to losslessly transcode existing JPEG files[14], reducing their size by about 20% while allowing them to be perfectly reconstructed back into the original JPEG. It also provides excellent lossy and lossless compression, progressive rendering, support for wide color gamuts, and high bit depths. While Chrome did remove support in late 2022, the decision was reversed. As of 2026, JPEG XL decoding support has been re-integrated into both Chrome (behind a flag in early 2026, enabled by default in Chrome 155)[15] and Firefox, following its adoption by Apple in Safari 17.

Responsive Images: Serving the Right Size

Choosing the right format is only half the battle. Sending a 2000-pixel-wide image to a phone with a 375-pixel-wide screen is wasteful. Responsive image techniques allow the browser to download the most appropriate image size for its current context.[23]

The srcset and sizes Attributes

The <img> element's srcset and sizes attributes are the core tools for serving appropriately sized images. They work together to provide the browser with the information it needs to make an intelligent choice.

  • srcset: This attribute provides a comma-separated list of candidate image URLs. Each candidate is paired with a descriptor: either a width descriptor (w) indicating the image's intrinsic width in pixels (e.g., image-800.jpg 800w) or a pixel density descriptor (x) for resolution switching (e.g., image-2x.png 2x). The width descriptor is more flexible and powerful for responsive layouts.

  • sizes: This attribute is frequently misunderstood but critically important. It tells the browser how large the image will be rendered in the layout across different viewport sizes. It uses a syntax similar to CSS media queries. For example, sizes="(max-width: 600px) 100vw, 50vw" tells the browser: "If the viewport is 600px or less, this image will take up 100% of the viewport width. Otherwise, it will take up 50% of the viewport width."

A common misconception is that srcset alone is sufficient. Without sizes, the browser defaults to assuming the image fills the entire viewport (100vw), which often causes it to download a larger image than necessary.

The browser's selection mechanism works like this:

  1. It evaluates the sizes attribute against the current viewport dimensions to determine the image's rendered width in CSS pixels.
  2. It checks the device's pixel ratio (e.g., 2.0 on a Retina display).
  3. It calculates the required image resolution by multiplying the rendered width by the pixel ratio.
  4. It examines the list of candidates in srcset and downloads the smallest image that has an intrinsic width greater than or equal to the required resolution.

The <picture> Element: Art Direction and Format Selection

The <picture> element provides more advanced control. It acts as a wrapper for one or more <source> elements and a final <img> element. The browser will evaluate each <source> in order and select the first one that matches.

This is useful for two main scenarios:

  1. Art Direction: When you need to serve a completely different image, not just a resized version, for different layouts. For example, a wide landscape shot on desktop could be replaced with a tight, vertically cropped portrait on mobile. This is achieved using the media attribute on the <source> element.

  2. Format Selection: You can offer modern formats like AVIF and WebP to browsers that support them, with a fallback to JPEG for older browsers. This is done using the type attribute.

Here is a concrete example combining format selection, responsive sizing, and a fallback:

<picture>
 <!-- Offer AVIF to supporting browsers -->
 <source 
 type="image/avif" 
 srcset="photo.avif?w=320 320w, 
 photo.avif?w=640 640w, 
 photo.avif?w=1024 1024w, 
 photo.avif?w=1280 1280w"
 sizes="(max-width: 768px) 100vw, 50vw">

 <!-- Offer WebP as the next option -->
 <source 
 type="image/webp" 
 srcset="photo.webp?w=320 320w, 
 photo.webp?w=640 640w, 
 photo.webp?w=1024 1024w, 
 photo.webp?w=1280 1280w"
 sizes="(max-width: 768px) 100vw, 50vw">

 <!-- Fallback to JPEG for all other browsers -->
 <img 
 src="photo.jpg?w=1024" 
 srcset="photo.jpg?w=320 320w, 
 photo.jpg?w=640 640w, 
 photo.jpg?w=1024 1024w, 
 photo.jpg?w=1280 1280w"
 sizes="(max-width: 768px) 100vw, 50vw"
 width="1280" 
 height="853"
 alt="A description of the photo.">
</picture>

Notice the <img> element is still required as the ultimate fallback and is what the browser actually renders. The width and height attributes are also present on the <img> to prevent layout shifts, a topic we'll cover next.

Loading Strategy: The Power of loading="lazy"

By default, browsers load all <img> elements as soon as they are discovered in the HTML, a behavior known as eager loading. This can delay the initial page render by requesting images that are not yet visible to the user (i.e., are "below the fold").

Native Lazy Loading

Modern browsers support native lazy loading via the loading attribute, which is now part of the WHATWG HTML standard[16]. Setting loading="lazy" on an <img> or <iframe> instructs the browser to defer loading the resource until it is about to enter the viewport.

The browser's mechanism is sophisticated. It doesn't wait until the image is 1 pixel away. Instead, it maintains a distance threshold that varies based on factors like network connection speed. For example, Chrome might start loading images when they are 1250px away on a fast connection but 2500px away on a slow one[17]. This pre-fetching ensures the image is likely loaded by the time the user scrolls to it.

Before native support, lazy loading was accomplished with JavaScript libraries that used the Intersection Observer API[18]. While still functional, the native attribute is preferred for its simplicity and because the browser can optimize the request timing even before any JavaScript has executed.

Tradeoffs and Common Mistakes

While powerful, loading="lazy" must be used correctly.

Do not lazy-load above-the-fold images. This is the most critical rule. Applying loading="lazy" to a hero image or any other content visible in the initial viewport is a performance anti-pattern. It will delay the discovery and loading of that critical image, negatively impacting the Largest Contentful Paint (LCP)[19] metric. Images in the initial viewport should use loading="eager" (or simply omit the attribute, as eager is the default).

Prevent layout shifts. When a lazy-loaded image finally loads, it can cause the content below it to shift downwards if its space was not reserved. This creates a jarring user experience and contributes to a poor Cumulative Layout Shift (CLS) score. To prevent this, always specify the image's dimensions. You can do this with width and height attributes on the <img> tag. Modern browsers use these attributes to calculate an aspect-ratio[20] and reserve the correct amount of vertical space before the image is loaded.

A Decision Framework for Technical Leaders

Manually optimizing every image is not a scalable or reliable strategy. A successful approach relies on automation and a clear set of policies.

1. Automate Image Transformation.
Implementing format selection and responsive sizing requires generating multiple versions of each uploaded image. This should not be a manual task. The two primary approaches are:

  • Image CDNs: Services like Cloudinary, Imgix, Akamai Image & Video Manager, or cloud-native solutions like AWS with Lambda@Edge handle image transformation on-the-fly. You upload one high-resolution original, and the CDN generates derivatives based on URL parameters. This simplifies development and offers advanced features but adds a direct service cost.
  • Build-Time Processing: Frameworks like Next.js (next/image) and Gatsby (gatsby-plugin-image), or standalone libraries like Sharp[21], can be integrated into your build process. This pipeline generates all necessary image variants when the site is deployed. This has a lower direct monetary cost but requires more engineering effort and infrastructure management.

2. Define a Format Strategy.
For maximum performance and compatibility, use the <picture> element to serve formats in order of preference: AVIF, then WebP, then a universal format like JPEG or PNG. This ensures that browsers receive the smallest possible file they can support.

  • Use AVIF/WebP/JPEG for photographic content.
  • Use AVIF/WebP/PNG for graphical content requiring transparency or sharp lines.

3. Implement a Sizing and Loading Strategy.

  • Always use srcset and sizes for any image whose rendered size can vary. Analyze your layouts to write accurate sizes attributes. Generate a set of image widths (e.g., 320w, 640w, 960w, 1280w, 1920w, 2560w) that efficiently covers the range of required resolutions.
  • Lazy-load by default. Apply loading="lazy" to all images that are not guaranteed to be in the initial viewport.
  • Eager-load critical content. Explicitly set loading="eager" (or omit the attribute) for the LCP element and any other images visible above the fold on initial load.
  • Always provide width and height attributes on <img> tags to prevent layout shift. This is non-negotiable for good user experience and CLS scores.

By adopting a systematic, automated approach to image optimization, you can deliver a significantly faster experience for your users, improve your Core Web Vitals, and reduce operational costs. It is a high-use engineering investment that pays continuous dividends.

Sources (25)
  1. Wikipedia: Chroma subsampling
  2. W3C: GIF89a Specification
  3. Wikipedia: Lempel - Ziv - Welch
  4. W3C: JPEG (ITU-T T.81)
  5. Wikipedia: Discrete cosine transform
  6. W3C: PNG (Portable Network Graphics) Specification
  7. IETF RFC 1951: DEFLATE Compressed Data Format
  8. Google Developers: WebP, a new image format for the Web
  9. IETF RFC 6386: VP8 Data Format and Decoding Guide
  10. Caniuse.com: WebP image format
  11. AOMedia: AV1 Bitstream & Decoding Process Specification
  12. Alliance for Open Media
  13. Caniuse.com: AVIF image format
  14. JPEG.org: JPEG XL
  15. developer.chrome.com
  16. WHATWG HTML Standard: Lazy loading attributes
  17. web.dev: Lazy-loading images
  18. MDN: Intersection Observer API
  19. web.dev: Largest Contentful Paint (LCP)
  20. MDN: aspect-ratio
  21. Sharp - High performance Node.js image processing
  22. Stoyan Stefanov, Web Performance Daybook Volume 2 ("O'Reilly Media, Inc.", 2012)
  23. Harley Ferguson, Strategic Leadership in Responsive Web Design (Packt Publishing Ltd, 2024)
  24. Stephen McGloughlin, Multimedia on the Web (Prentice Hall, 1997)
  25. S. S. Niranga, Mobile Web Performance Optimization (Packt Publishing Ltd, 2015)

Recommended reading

Core Web Vitals: What Google Measures and Why It Matters13 min readA comprehensive technical reference on Google's Core Web Vitals, explaining how the LCP, INP, and CLS metrics are measured, their impact on SEO, and the strategic tradeoffs for engineering leaders.The Evolution of CSS Layout: From Tables and Floats to Flexbox and Grid7 min readFor much of the web's history, we built page layouts with tools that were never designed for the job. The story of CSS layout is the slow arrival of tools that actually fit the problem, and why the old hacks were not anyone's fault.The Evolution of Web Rendering: From jQuery to SSR, SSG, and ISR7 min readWhere a web page gets built, on the server or in the browser, has swung back and forth for twenty years. Each swing solved the previous era's pain and created new pain of its own. Here is the full arc, and why it is not going in circles.Fastly: The Edge Cloud and CDN Company13 min readFastly is a technology company providing a programmable edge cloud platform, including a content delivery network (CDN), security services, and serverless computing, designed to accelerate and secure websites and applications.The Origins of PHP: The Accidental Language That Runs Much of the Web6 min readPHP was never meant to be a programming language. It started as a few tools one developer wrote to track visits to his resume, survived an existential threat from Facebook, and still runs a large share of the web. Here is how.A Definitive History of the Computer Mouse16 min readA comprehensive, chronological history of the computer mouse, from Douglas Engelbart's first wooden prototype in 1964 to the modern optical, laser, and wireless devices that are ubiquitous in personal computing.