How do I handle responsive images with srcset?
Responsive images use the srcset and sizes attributes to serve different image versions based on screen size, pixel density, and viewport width, improving performance and user experience.
Understanding srcset:
The srcset attribute contains a comma-separated list of image URLs with descriptors:
- Width descriptors:
example-small.jpg 480w, example-medium.jpg 800w, example-large.jpg 1200w - Pixel density descriptors:
logo.jpg 1x, logo@2x.jpg 2x
The browser automatically selects the most appropriate image based on device capabilities.
The picture element:
The <picture> element provides more control, allowing different images for different media queries:
<picture>
<source media="(min-width: 800px)" srcset="large.jpg">
<img src="small.jpg">
</picture>
Extraction strategies:
When extracting responsive images, you need to decide which version to use:
- Extract all versions and let your application choose
- Extract the largest for maximum quality
- Extract the smallest for faster downloads
- Extract based on your target use case
Implementation:
Parse the srcset attribute by splitting on commas and extracting URLs and descriptors. For <picture> elements, iterate through <source> tags and their media queries.
Some sites use JavaScript libraries like Picturefill to polyfill responsive image support in older browsers, which may require executing JavaScript to see final image URLs. Browser DevTools show which image version was actually loaded.
Important note:
When scraping, consider that different images may contain different content (not just different sizes), such as cropped versions for mobile.
Our Image Extractor parses both srcset and <picture> elements to show all available image versions.