Images are critical for every website and web application today. As images can be quite large, they can have a big impact on the percieved performance (and than I don't even mention the bandwith cost).
Before you start converting all your images to the webp format or implementing all kind of crazy javascript and css hacks, I’ll learn you a simple trick that could help you a lot…
You can lazy load your images using the loading attribute. By using lazy loading, the images in your application or site will only be loaded when they become in reach of the visible are of your website. So as long as a user doesn’t scroll, only what is visible at that moment will be loaded.
Here is a simple example:
<img src="example.jpg" loading="lazy" alt="..." />
The following values are supported by the loading attribute:
- lazy - Deferring the loading of assets till it reaches a certain distance from the viewport.
- eager - loading the assets as soon as the page loads, irrespective of where they are placed on the page, whether above or below the page fold.
- auto - This value triggers default lazy loading. Basically, it's the same as not including the loading attribute.
This feature is supported on most browsers (check caniuse) and if your browser doesn’t know this attribute it will just be ignored and your image will load immediatelly(which I think is an OK fallback).
Remark: If you want the remaining content from reflowing when a lazy-loaded image is downloaded, you can set the height
and width
attributes to the <img>
element up front.