Browser is loading two images - one for srcset, one for src (Chrome 41 et al)

余生颓废 提交于 2019-12-10 14:45:29

问题


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


来源:https://stackoverflow.com/questions/29715791/browser-is-loading-two-images-one-for-srcset-one-for-src-chrome-41-et-al

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!