3 attributes your images must have!
They say a picture tells a thousand words. It certainly costs a thousand words when it comes to performance! Images tend to be quite large files, so take a while to load. They also block rendering so they have to complete before content further down the page can load.
But there is hope! We can make images lazy and get out the way of the rest of the page with some simple attributes!
First thing first, make sure your images are as small as possible in the first case. I'd highly recommend Squoosh by the Chrome team which you can use to optimise the size of your images.
Here's a current image on a website:
<img src="some_image_file.png" />
We can improve the loading of this image with a few attributes, like so:
<img src="some_image_file.png" loading="lazy" decoding="async" alt="A Description of the image" />
Lets dig into those attributes.
It has wide browser support now, and if the browser doesn't support it, it will just be ignored, so no excuse not to add it!
It can have the values of
Eager is the default value, meaning it will load the image immediately regardless of if the user can currently see the image.
Lazy allows the browser to decide when to load the image, which is will do when the user is nearer the content. Meaning we don't have to load a full page of images straight away, only the ones we can see immediately.
This is supported across all browsers. This gives the browser a hint on how you want your image to be decoded, either synchronously or asynchronously. Either getting in the way of the rest of your content or not.
This doesn't impact loading performance. But please use it! 🙏 It takes very little effort to add and helps make your site more accessible! The best way to come up with the value is to imagine you are describing the image to your friend over the phone, how would you do it. This is exactly how the alt attribute functions to screen readers so please use it!
Background images are a bit more tricky to be lazy loading.
Firstly I would really try not to use background images as they aren't great for accessibility, so if at all possible use a normal image element.
In summary, these 3 attributes improve the performance of your website with minimal effort! There is no browser support issues or any reason not to use them, so add them to your images now!
These attributes also work is you are using a picture element, just set them on the image element as normal. Here's an example of using a picture element for switching images based on dark mode or not.
<picture> <source srcset="/images/linkedin-white.webp" media="(prefers-color-scheme: dark)" /> <img class="linkedin" src="/images/linkedin.webp" alt="LinkedIn Profile" loading="lazy" decoding="async" /> </picture>
They also work is you are using a image element, with multiple sized images via
Add these 3 simple attributes to your images right now!