I'm using the srcset attribute on a web page I'm developing.
<img src="img/picture-820x496.jpg"
srcset="img/picture-820x496.jpg 1200w,
img/picture-374x226.jpg 992w,
img/picture-305x185.jpg 768w,
img/picture-707x428.jpg 300w" />
If I check which resources get loaded with the page, I see that Chrome 41 as well as FF using the polyfill as well as Safari 7 always load the image twice - once the full resolution and once the according size from the srcset attribute. What am I doing wrong here?
Each image in srcset can be taken. So if you want to control, what is used or not used, you need to use the picture element.
srcset defines the set of images we will allow the browser to choose between, and what size each image is. Each set of image information is separated from the previous one by a comma.
The srcset Attribute. On regular resolution displays, the 1x variant of the srcset will be used [1x image]. On displays with 2 device pixels per CSS pixel, the 2x variant of the srcset will be used [2x image]. Similarly, there is a 3x image, and a 4x image.
The srcset attribute allows you to specify a list of image file URLs, along with size descriptions. Yo ualso need to still use the src attribute to identify a “default” image source, to be used in browsers that don't support srcset .
I had a similar problem, I found that if the src
image was not one of those available in the srcset
images the browser would load the src
image regardless. The solution was to ensure the src
image url matched one of the srcset
images urls.
As an aside - as I understand the spec the w
value following the image url should match (roughly) the width of the image. This allows the browser to best determine the image to display based on the sizes
attribute and device pixel density. So you should probably alter the w
values in your markup and add the sizes
attribute (which allows you let the browser know the rendered image size using media queries and a fallback ie. (min-width: 640px) 600px, 50vw
). Consider the example below:
<img src="img/picture-820x496.jpg"
srcset="img/picture-820x496.jpg 820w,
img/picture-707x428.jpg 707w,
img/picture-374x226.jpg 374w,
img/picture-305x185.jpg 305w"
sizes="100vw">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With