<srcset>
As mobile devices become increasingly prevalent, optimizing images for web performance is more important than ever. To ensure that websites load quickly on mobile devices, it's recommended to keep total page weight below 500kb, and to use techniques like lazy loading and optimizing images to minimize network and CPU time.
One solution to the issue of varying device resolutions is the srcset attribute. This attribute allows developers to specify different images for different device resolutions, allowing the browser to choose the most appropriate image based on the device's characteristics. However, this approach requires pre-processing of multiple images and can add complexity to the developer workflow.
<img
srcset="/images/bluehat.jpg 1x,
/images/bluehat.jpg 2x,
/images/bluehat.jpg 3x"
src="/images/bluehat.jpg"
>
A more modern approach to responsive images is to use the w and dpr URL parameters offered by image transformation services like Peakhour. This method enables developers to use a single master image and avoid the complexities of generating and uploading multiple images to their site.
<img
srcset="/images/bluehat.jpg?w=400 1x,
/images/bluehat.jpg?w=400&dpr=2 2x,
/images/bluehat.jpg?w=400&dpr=3 3x"
src="/images/bluehat.jpg?w=400"
>
With this approach, the browser selects the best resolution for each device based on its DPR capabilities, simplifying the development and deployment process.
In addition to srcset, the sizes attribute can be used to target image sizes based on media queries. This attribute, combined with srcset, gives developers the ability to choose different image resolutions based on the size of the viewport.
<img
srcset="/images/bridge.jpg?w=1024&h=1024&fit=crop ;1024w,
/images/bridge.jpg?w=640&h=640&fit=crop ;640w,
/images/bridge.jpg?w=480&h=480&fit=crop ;480w"
src="/images/bridge.jpg?w=640&h=640&fit=crop"
sizes="(min-width: 36em) 33.3vw, 100vw"
>
Using srcset and sizes attributes provides an effective solution for optimizing images for responsiveness and ensuring optimal performance on mobile devices. By utilizing image transformation services and combining srcset with sizes, developers can simplify the process and achieve the best possible resolution for each device.