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, 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
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
srcattribute is selected.
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.