I was recently looked at the speed of the Waitrose homepage and was surprised by its massive uncompressed HTML document size: 3.5 MB.
This article takes a look at how images make the document so big and asks if this reduces site speed.
Image URLs in the srcset attribute
Traditional img
tags only take one src
image URL that's used regardless of the size of the device. That means either images will look pixelated on large high-res screens, or a lot of unnecessary bandwidth will be consumed on small devices.
<img src="img-800px.png">
The srcset
and sizes
attributes fix this problem. Developers can use srcset
to provide multiple URLs that serve the same image at different sizes – or sometimes a different image that uses the available space more effectively. sizes
is used to tell the browser how large the image is supposed to be at different screen sizes.
The browser then decides what image to load based on the rendered size and screen resolution.
<img
srcset="img-400.png 400w, img-800.png 800w, img-1600.png 1600w"
sizes="(max-width: 600px) 400px, 800px">
Using lots of srcset URLs
Now let's take a look at the HTML of the Waitrose homepage.
This section of the page looks pretty simple, but it's built with half a megabyte of HTML code.
The website is responsive and uses the picture
tag and srcset
attribute to serve different images at different screen sizes. Each <picture>
tag in this section contains 180 possible image URLs.
On top of that, the website uses Bootstrap classes like visible-xs
to show different DOM elements depending on screen size. Each of the three blocks contains mostly similar content, and the browser ends up loading one image out of 540 possible URLs.