Can’t make #ChromeDevSummit this year? Catch all the content
(and more!) on the livestream or join your peers for a CDS Extended event at
a hosted location nearby. To learn more, check out the Chrome Dev Summit
This article gives me an opportunity to discuss two of my favorite things: responsive images and preload. As someone who was heavily involved in developing both of those features, I'm super excited to see them working together!
Suppose you're browsing the web on a screen that's 300 pixels wide, and the page just requested an image that's 1500 pixels wide. That page just wasted a lot of your cellular data because your screen can't do anything with all of that extra resolution. Ideally, the browser should fetch a version of the image that's just a little wider than your screen size, say 325 pixels. This ensures a high-resolution image without wasting data. And, even better, the image will load faster. Responsive images enable browsers to fetch different image resources to different devices. If you don't use an image CDN need to save multiple dimensions for each image and specify them in the srcset attribute. The w value tells the browser the width of each version. Depending on the device, the browser can choose the appropriate one:
Preload lets you tell the browser about critical resources that you want to load as soon as possible, before they are discovered in HTML. This is especially useful for resources that are not easily discoverable, such as fonts included in stylesheets, background images, or resources loaded from a script.
Responsive images and preload have been available for the last few years, but at the same time something was missing: there was no way to preload responsive images. Starting in Chrome 73, the browser can preload the right variant of responsive images specified in srcset before it discovers the img tag!
To preload responsive images, new attributes were recently added to the <link> element: imagesrcset and imagesizes. They are used with <link rel="preload"> and match the srcset and sizes syntax used in <img> element.
For example, if you want to preload a responsive image specified with:
<imgsrc="wolf.jpg"srcset="wolf_400px.jpg 400w, wolf_800px.jpg 800w, wolf_1600px.jpg 1600w"sizes="50vw"alt="A rad wolf">
You can do that by adding the following to your HTML's <head>:
Let's say you're dynamically-loading hero images as part of a slideshow and know which image will be displayed first. In that case, you probably want to avoid waiting for the script before loading the image in question, as that would delay when users can see it.
You can inspect this issue on a website with a dynamically-loaded image gallery: