Browser is loading two images - one for srcset, on

2019-06-26 03:12发布

问题:

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?

回答1:

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">