I recently reduced the total image transfer size for the entire Projects subpage by 93% (36 MB to 2.5 MB) and the initial-load image transfer size by over 99% (36 MB to 0.2 MB). While this site is built with Astro, the used techniques are applicable for most website-building technologies and can provide sizeable performance improvements.
Optimization methods
In this section, we go over the techniques I used to achieve the aforementioned results. We start with simple steps and then move on to more modern and advanced, yet still simple and well-supported, approaches. Although each subsection is independent, I recommend at least skimming through all of them.
Better formats
Among the most popular image formats, we have to mention JPEG and PNG. They can be used similarly but feature different strengths and weaknesses. JPEG is a lossy format, and it sacrifices some quality for a smaller file size. On the other hand, PNG is lossless and retains all the image quality but results in larger files. It also supports transparency, which JPEG does not. Clearly, if we want to optimize for size, JPEG emerges as the better choice. However, it is not always the best option; for instance, PNG is much better for pixel art or fancy logos.
Thankfully, nowadays, we have even better alternatives, namely WebP and AVIF. They both provide almost 2x smaller
files [1], while being supported for circa 95% of users [2]. If you must support
older browsers, you can also use the <picture>
element to provide a fallback image in a uniformly supported format, such as JPEG. Unlike their predecessors, WebP
and AVIF support both lossy and lossless compression, and I’d generally recommend lossy for photographs or screenshots.
In the case of the project page, I used WebP, as it is slightly better supported and is also the default for Astro’s image utilities. For instance, converting the image for the first project from JPEG to a high-quality WebP, the file size went down from 975 KB to 150 KB, an 85% reduction, with no visible quality loss.
It has to be noted that if you can use vector graphics, you should instead use SVG, which makes sure that the image is sharp at any resolution and also has a tiny file size. This includes icons, logos, and illustrations. For instance, the wave effects on the About page are a perfect fit, as well as the skill icons on project cards.
Correct sizing
Knowing the dimensions of the image, both rendered and original, is crucial for optimization. Firstly, it doesn’t make sense to use a 2000 px wide image if it is never displayed larger than 500 px. For the portfolio, the project cards are bound to at most 1024 px across, while the image files had a width of 1200 px. Downscaling the images to 1024 px reduced the file size by 15% to 30%, depending on the project.
Secondly, the width and height attributes allow the browser to reserve space for the image before it is loaded. This
prevents content shift, which can be jarring for users and is a negative factor for the Core Web Vitals.
This can be beneficial even if the image is scaled using CSS [3]. Explicit dimensions do not speed up the loading of the image
but make the experience smoother regardless.
Responsive images
Unless our images are small icons, they are likely to be displayed at different sizes on different devices. For instance,
a full-width landing image on a desktop is several times larger than the same image on a mobile device. The widely
supported [2] srcset and
sizes attributes allow us to provide multiple
versions of the same asset, each optimized for a specific screen. We refer to this concept as responsive images.
The srcset attribute lists available image files and their widths, while the sizes attribute describes how big the image
will be in different contexts. The browser can then combine these values to select the best image for the current viewport.
In the simplest case, we want to display a full-width image on each device but do not want to load a huge image on mobile.
We can use the srcset attribute to provide different versions of the image and set the sizes attribute to 100vw (which
is also the default value). This signals that the image will always take the full viewport width. The full example looks like this:
<img src="hero-1536.webp" alt="Hero image of the amazing website." width="1536" height="864" srcset="hero-640.webp 640w, hero-768.webp 768w, hero-1024.webp 1024w, hero-1280.webp 1280w, hero-1536.webp 1536w" sizes="100vw"/>Additionally, the <picture> element can be used to
provide different images for different screen sizes but also to provide fallbacks for browsers that do not support modern formats.
Other attributes
There are three other attributes that should be covered. They do not reduce transferred sizes but optimize the loading and rendering of the images, improving user experience and Core Web Vitals performance. They are:
fetchpriority– eitherhigh,low, orauto. You can set it tohighfor critical images, which are large and immediately visible on the page, and can be left asautofor others.decoding– eithersyncorasync. Forsync, the browser decodes the image synchronously, whileasyncallows for other rendering while the image is being decoded.loading– eithereagerorlazy. Foreager, the image is loaded immediately, whilelazydefers loading until the image is close to being visible. This is useful for images below the fold, which do not have to be ready straight away.
Combining everything in Astro
Some modern static site generators provide built-in image optimization features, streamlining the process of format conversion,
compression, and responsive images. For instance, we have Next.js’s Image,
Nuxt’s NuxtImage, and Astro’s Image.
For a long time, this Astro component was not used on the project page, as each project card forms a React
island to allow for interactivity. While Astro components can use React components,
the other way around is not possible (outside using slots), meaning that Image could not be used for the project showcase.
However, there is also a getImage function that can generate
images for use outside Astro components. This includes React, as getImage simply returns an object with the HTML attributes for the
picture. The only caveat is that the function must be used in a server-only context, so we have to call it in Astro and propagate the result
using props.
To do this, I renamed the ProjectCard React component responsible for displaying a single project to ProjectCardInner and made a new
ProjectCard Astro file for a server-side wrapper. The shortened version of the code looks as follows:
---import { getImage } from "astro:assets"import ProjectCardInternal from "./ProjectCardInternal"
const { project } = Astro.propsconst image = await getImage({ src: project.image, layout: "constrained" })---
<ProjectCardInternal client:visible {project} {image} />The image prop undergoes some basic processing; for instance, Astro produces fetchpriority, while React expects fetchPriority (with
a capital P), so we rename the attribute. We also add the alt attribute for proper accessibility. Afterwards, the attribute dictionary
can be simply spread into the <img> tag in the React component:
export default function ProjectCardInternal({ project, image }) { // we can implement any client-side logic here return <img {...image} />}When visiting the rendered page, we notice that the images now use WebP, are correctly sized and responsive, and have the additional attributes. Astro automatically handled the conversion and quality optimization and correctly emitted differently sized images into the build bundle. The images on the project page have roughly the following HTML:
<img src="/_astro/tchojnacki-dev.UpSx2R8V_Z10mK3R.webp" alt="tchojnacki.dev" width="1024" height="4007" srcset="/_astro/tchojnacki-dev.UpSx2R8V_ZttQAw.webp 640w, /_astro/tchojnacki-dev.UpSx2R8V_Z1rk4CS.webp 750w, /_astro/tchojnacki-dev.UpSx2R8V_mtAaJ.webp 828w, /_astro/tchojnacki-dev.UpSx2R8V_Z10mK3R.webp 1024w" sizes="(min-width: 1024px) 1024px, 100vw" loading="lazy" decoding="async" fetchpriority="auto"/>Conclusion
Proper usage of modern HTML image features can significantly reduce the loading time, transfer size, and Core Web Vitals
compliance of your website. The described techniques are well-supported in both the frameworks and browsers, and if you
require high backwards compatibility, the <picture> element can be used to provide fallbacks.
I purposefully covered only the HTML features to ensure the universal applicability of the techniques. However, if you have higher control over your back end and deployment stack, you can also look into caching, CDN, and server-side image optimization. At the same time, the accessibility of images should not be overlooked. Make sure to follow at least the guidelines outlined by the web.dev guide.