Optimizing images on the web
Source set, WebP, lazy-loading
Optimizing images is a crucial step toward high-quality websites. But it is often a process that is not taking into account by many software developers. Let’s review the common ways we can use to optimize images easily at this point in time.
Use a source set
Building a responsive website means you will have to consider more than one resolution. One device can have a small resolution on a smartphone and the other a high resolution on a 4k monitor. The <img>
element has a src
attribute that lets you specify the source of the image. But this image will be applied to every device, regardless of their resolution.
To fix this problem, we have another attribute called srcset
. With srcset
, we can provide additional source images and let the browser appropriate image to load. The source set is a list of URL and sizes separated by ,
.
Use WebP
WebP is a modern image format that provides superior lossless and lossy compression for images on the web. Using WebP, webmasters and web developers can create smaller, richer images that make the web faster. WebP lossless images are 26% smaller in size compared to PNGs.
WebP was first released in 2010, and it is soon going to be available in all major browsers. It took some time, I know. At the time of this writing, only Safari doesn’t support WebP. You can check the support on caniuse.
If WebP is not yet available on every browser, how can we still use it? We can use a <picture>
element. The picture element works similarly as video and audio and takes <source>
elements as children. Each source can have a source set, which lets you define a source set in type image/webp and type image/jpeg.
The browser will consider each child
<source>
element and choose the best match among them. If no matches are found—or the browser doesn't support the<picture>
element—the URL of the<img>
element'ssrc
attribute is selected.
Lazy Loading
Images are a resource that can be heavy on a webpage. You don’t always look at a page in its entirety. Why would you load images at the bottom of the website if most of your users will not scroll that far? That is the reason why you would want to lazy load your images. You can lazy load your images with javascript and intersection observer API, or you can now do it in HTML directly.
A new attribute of the <img>
element is called loading
. And one of the available value is lazy
. It provides a native way for browsers to know which images should be loaded lazily and makes it simple for developers to use this technique.
About the author
I’m Floriel, a software engineer at Full Human. I grew up reading stories about heroes. Those fictional characters have been my role models. I aspire to work hard to reach their level and become a better human being every day. You can follow me on GitHub and Twitter.