Using imgix.js with srcset for resolution switching
When people think responsive images, they usually think “resolution switching.” Resolution switching is serving a different resolution image to different devices. The content, crop, and composition of the image remains the same, but the resolution changes.
imgix is a service uniquely equipped to handle this case. All renders are generated on the fly and cached at edge locations around the globe. With imgix.js, implementing resolution switching is simple:
<img ix-src= "https://assets.imgix.net/examples/moon.jpgw=400&h=300&fit=crop&crop=entropy"
sizes="(min-width: 768px) 540px, 100vw"
alt="A photo of the moon">
Upon initialization, imgix.js will augment any image element with the ix-src attribute to generate an exhaustive srcset definition. Here’s what you will see under the hood if you inspect the element:
<img ix-src= "https://assets.imgix.net/examples/moon.jpg?w=400&h=300&fit=crop&crop=entropy"
sizes="(min-width: 768px) 540px, 100vw"
srcset="
https://assets.imgix.net/examples/moon.jpg?w=100&h=75&fit=crop&crop=entropy 100w,
https://assets.imgix.net/examples/moon.jpg?w=210&h=158&fit=crop&crop=entropy 210w,
...
https://assets.imgix.net/examples/moon.jpg?w=2618&h=1964&fit=crop&crop=entropy 2618w.
"
src= "https://assets.imgix.net/examples/moon.jpgw=400&h=300&fit=crop&crop=entropy"
alt="A photo of the moon">
ix-initialized="ix-initialized">
The resulting image will be loaded in at 540 logical pixels wide on tablets and desktops, thanks to the (min-width: 768px) 540px rule. It will be loaded at 100% viewport width (100vw) on mobile screens. Modern browsers will select an appropriate image from the local cache if available. If no appropriate image is available, it will request a new image at the targeted w that it needs.
Browsers running on devices with high-density displays will select the image most appropriate for their resolution. In this example, an iPhone 6S will select the 750w URL from the srcset attribute. This is because the iPhone 6S is 375 logical pixels wide, but has a screen density of 2x. Thus, 375 × 2 = 750.
The result is that just the right image is loaded for each device and browser. imgix.js is able to easily handle resolution switching by generating srcset attributes.