Web image optimization best practices techniques in 2022

This article is over 4 years old

Published . Tools, APIs and best practices may have moved on since, so some steps or recommendations might no longer apply. Check the linked official documentation for the latest guidance.

As well as being vital for providing users with a quick to load experience, image optimisation is now set to play a key role in SEO with the increased importance of Google’s Core Web Vitals in determining ranking. Let's look at some of the things to think about when working with images in our application.

Published:

As well as being vital for providing users with a quick to load experience, image optimisation is now set to play a key role in SEO with the increased importance of Google’s Core Web Vitals in determining ranking. Let's look at some of the things to think about when working with images in our application.

Core Web Vitals are the subset of Web Vitals that apply to all web pages, should be measured by all site owners, and will be surfaced across all Google tools. Each of the Core Web Vitals represents a distinct facet of the user experience, is measurable in the field, and reflects the real-world experience of a critical user-centric outcome.

The metrics that make up Core Web Vitals will evolve over time. The current set focuses on three aspects of the user experience: loading, interactivity, and visual stability. At the time of writing, these were expected to become ranking indicators in early 2022:

  • Largest Contentful Paint (LCP) measures loading performance. To provide a good user experience, LCP should occur within 2.5 seconds of when the page first starts loading.
  • First Input Delay (FID) measures interactivity. To provide a good user experience, pages should have an FID of 100 milliseconds or less.
  • Cumulative Layout Shift (CLS) measures visual stability. Pages should maintain a CLS of 0.1 or less.

As part of your development process for adding new pages, periodic reviews, or changes to existing pages, use the following checklist to improve image performance and Core Web Vitals. The checklist is largely arranged in order of increasing complexity.

Tools like Google Chrome Lighthouse in the developer tools are useful for identifying and prioritising improvements.

Are alt tags necessary?

Adding alternative text to images is first and foremost an accessibility principle. Screen readers announce an alt attribute to help visually impaired users understand an on-page image. Alt text is also displayed in place of an image if it cannot load, and provides context to Googlebot and other crawlers to help them index images appropriately.

Images generally fall into two categories:

  • Images that do not convey additional meaning and are considered decorative.
  • Images that convey meaning and add to the understanding of a page.

Decorative images do not need to be announced by a screen reader. Addingrole="presentation" or an empty alt attribute (which has marginally better support) are valid ways to handle these images, and prevent them from being announced to screen reader users.

Further reading:W3C WAI: Decorative Images.

Should images have explicit widths and heights?

In 2022, definitely. Historically, setting width and height attributes on HTML images was an anti-pattern. However, they are now an important part of avoiding layout shift. Layout shifts can be frustrating when elements move around and make a page appear visually jarring.

Avoiding large layout shifts is essential to delivering a smooth experience and improving Google page experience metrics.

Image and video elements without explicit dimensions are often resized using CSS. The browser can only determine their dimensions and allocate space after it starts downloading these unsized assets.

The width and height values do not need to match the rendered size. The browser uses them to calculate the image's aspect ratio:

HTML
<!-- The empty alt marks this as a decorative image -->
<img src="flowers_300x300.jpg" alt="" width="160" height="90" />
<!-- The browser still computes a 16:9 aspect ratio -->

As long as the aspect ratio is consistent across viewports, you can set width and height to any values that produce the same ratio:

HTML
<!-- The empty alt marks this as a decorative image -->
<img src="flowers_300x300.jpg" alt="" width="320" height="180" />
<!-- The browser still computes a 16:9 aspect ratio -->

CSS typically sets images to a maximum width of 100%, allowing an image to resize within its container:

CSS
img {
  max-width: 100%;
}

However, if the image has an explicit height and CSS overrides only its width, the image may stretch or squash because its aspect ratio is no longer maintained. The fix is straightforward:

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

When is the CSS property aspect-ratio appropriate?

The CSS aspect-ratio property is not usually needed for HTML image elements, since the browser computes their ratio from the width and height attributes. It can be useful when an image is set as a CSS background on a div, keeping the element's ratio consistent as it grows or shrinks.

What base image format is best for my website image?

There are many image formats available for the web. PNG is often used where JPEG would be sufficient, making the image file much larger than necessary. Progressive enhancement with WebP is covered below.

JP(e)G

JPEG uses lossy compression that takes advantage of human perception. It can achieve compression ratios of 1:10 without a perceivable difference in quality, though compression artefacts become more prominent beyond that. Because JPEG compression averages colours of nearby pixels, it is best suited to photographs with smooth variations in colour and intensity. It is less suitable for text or lines that need sharp contrast. Transparency is not supported.

PNG

PNG is a lossless image format: no data is lost during compression and no compression artefacts are introduced. It retains sharp detail better than JPEG, but occupies more disk space. This makes it unsuitable for high-resolution photographs, but a good choice for text, logos, shapes with sharp edges, and images needing transparency.

GIF

Like PNG, GIF is lossless. It was favoured for simple website graphics when PNG support was still growing. PNG is now supported across major devices and compresses about 5–25% better than GIF, so GIF is mainly used when an image needs animation.

SVG

SVG is a format for two-dimensional vector and vector-raster graphics designed for the web. It supports animation, transparency, and gradients, and scales without losing quality. It is generally a good choice for simple line art such as icons.

Should I properly size and compress website images?

For sure. Sometimes supplied assets are obviously too large and can be resized. As a rule of thumb, an image should be no more than twice as wide as its maximum rendered size. This helps keep images crisp on retina or other high-density displays.

Compression is often overlooked because we assume third-party assets are already optimised. Try compressing images further with desktop design tools or services such as TinyPNG andTinyJPG. Make sure compression does not compromise visual quality or user perception.

What is WebP? Should I use it?

WebP supports lossy and lossless compression, animation, and alpha transparency. Developed by Google, it is designed to create files that are smaller at the same quality, or higher quality at the same size, than JPEG, PNG, and GIF.

Not all browsers support WebP, so treat it as progressive enhancement. The picture element lets you provide a fallback:

HTML
<picture>
  <source type="image/webp" srcset="/assets/images/flowers.webp" />
  <img src="/assets/images/flowers.png" alt="" />
</picture>

Can I use WebP with CSS background images?

WebP support for CSS background images is different. Unlike an HTML element, CSS has no optimal built-in fallback mechanism. Multiple backgrounds may cause both resources to download, which is a performance concern. Feature detection provides a solution. A 3 KBcustom Modernizr buildcan detect WebP support and add a class to the body. CSS can then provide the fallback:

CSS
.no-webp .hero-banner {
  background-image: url("image.jpg");
}
.webp .hero-banner {
  background-image: url("image.webp");
}

What is native image lazy loading?

Lazy loading has historically been implemented with JavaScript to defer resources until they are needed. On pages with many images, the idea is to load them as the user scrolls near them instead of downloading every image on page load. A user may never scroll far enough to view some images, so delaying their download can save resources. Native lazy loading is now supported by most browsers; browsers without support load images normally.

The loading attribute lets a browser defer loading offscreen images and iframes until users scroll near them. It supports three values:

  • lazy: a good candidate for lazy loading.
  • eager: not a good candidate; load immediately.
  • auto: the browser decides whether to lazy load.
HTML
<img
  src="flowers_300x300.jpg"
  loading="lazy"
  alt="" />

Should I lazy load all images?

Do not simply add lazy loading to every image. Images above the fold that are lazy loaded may take a performance hit. The fold differs by viewport, so my approach is to lazy load images that are below the fold across common viewports. Native lazy loading keeps the implementation simple.

Browsers use several factors to decide when to load lazy content, not just scroll position. Connection speed can also help determine when an image should load so it is ready when needed.

After page changes, images that used to be below the fold may move above it, and vice versa. Review lazy-loaded images periodically to make sure they are still appropriate.

How can I serve retina images separately?

Suppose an image is 300 by 300 pixels on mobile and 100 by 100 pixels on desktop in a three-column grid. The base image should be 600 by 600 pixels: twice the largest rendered size to support high-density Retina displays.

Without WebP variations, srcset can offer standard- and high-density versions, with a regular src fallback for browsers that do not support srcset:

HTML
<img
  srcset="flowers_300x300.jpg 1x, flowers_600x600.jpg 2x"
  src="flowers_300x300.jpg"
  alt="" />

On a non-retina desktop display, the browser requests the smaller 300-by-300 image rather than the 600-by-600 version, improving performance. Retina devices can request the higher-quality image.

We should also provide WebP variants. This requires more image files, but provides both formats at each density:

HTML
<picture>
  <source type="image/webp" srcset="flowers_300x300.webp 1x, flowers_600x600.webp 2x" />
  <source type="image/jpeg" srcset="flowers_300x300.jpg 1x, flowers_600x600.jpg 2x" />
  <img alt="" src="flowers_300x300.jpg" srcset="flowers_300x300.jpg 1x, flowers_600x600.jpg 2x" />
</picture>

This offers the best of both worlds, but there is still a problem with fully responsive images:

  • On a non-retina mobile display, we download a 600-by-600 image when a 300-by-300 image would be sufficient.
  • On a non-retina desktop display, we download a 600-by-600 image when a 100-by-100 image would be sufficient. The next section covers how to address this.

How can I serve fully responsive images?

Fully responsive images can improve performance, though they come with greater development and maintenance costs. This approach may be best reserved for the largest images.

Using srcset with sizes still serves the same image at multiple sizes, but gives the browser enough information to choose based on pixel density and layout size.

Simple example

Excluding WebP variations for brevity, a simple implementation looks like this:

HTML
<img
  alt=""
  srcset="flowers_300x300.jpg 300w, flowers_600x600.jpg 600w"
  sizes="
    (max-width: 500px) calc(100vw - 48px),
    (max-width: 1023px) calc(0.333 * (100vw - 48px)),
    calc(0.333 * (100vw - 48px))"
  src="flowers_300x300.jpg" />

We are providing multiple copies of the same image and letting the browser choose the most appropriate one. Instead of annotating them with pixel density (x) we label them with resource width, using w descriptors. Ifflowers_300x300 is 300 by 300 pixels, it is labelled300w.

Using srcset with width descriptors requires asizes attribute so the browser knows how much space the image will occupy. Without this information, browsers cannot make smart choices.

In the example above:

  • At the smallest size, the image is full width in a div with 24 pixels of horizontal padding on each side, so sizes should becalc(100vw - 2rem).
  • At the medium size, a three-column image grid has 24 pixels of horizontal padding on each side, so usecalc(0.333 * (100vw - 48px)).
  • At the largest size, the three-column grid has 48 pixels of horizontal padding on each side, so usecalc(0.333 * (100vw - 48px)).

The RespImageLintbookmarklet can help debug common issues with the sizesattribute.

The browser also accounts for pixel density automatically. Retina screens are likely to receive a larger image than standard-density screens.

Creating sizes attributes can be tricky and time-consuming. The attribute describes how wide the image appears within a specific site layout, so it is closely tied to the site's CSS. Image width depends on layout as well as viewport size. Account for margins and padding at every breakpoint when calculating values. This can become brittle: if a shared grid's spacing changes, its sizesattribute may become invalid and the browser may serve a different image than expected.

Responsive images, with WebP

Adding WebP support makes the code more complex:

HTML
<picture>
  <!-- Load WebP in different sizes if the browser supports it -->
  <source
    type="image/webp"
    srcset="flowers_300x300.webp 300w, flowers_600x600.webp 600w"
    sizes="
      (max-width: 500px) calc(100vw - 48px),
      (max-width: 1023px) calc(0.333 * (100vw - 48px)),
      calc(0.333 * (100vw - 48px))"
  />
  <img
    srcset="flowers_300x300.jpg 300w, flowers_600x600.jpg 600w"
    sizes="
      (max-width: 500px) calc(100vw - 48px),
      (max-width: 1023px) calc(0.333 * (100vw - 48px)),
      calc(0.333 * (100vw - 48px))"
    src="flowers_300x300.jpg"
    alt=""
  />
</picture>

Wrap up

Thanks for reading. I hope you've learned techniques to help optimize website images so you can benefit from faster load times, a better user experience, and hopefully more leads.