Responsive image, picture vs img with srcset, fallback issue

无人久伴 提交于 2020-12-05 11:17:43

问题


After reading all day about one method or the other I am still not sure what is the best for me, all sites explain the same thing but when I want to know the things that really worries me, nobody talks about that.

My case: I have almost all my images using width 100% and height to auto, and the image containers had dynamic size, for example 30vw, or 40%, etc. (not sure if in this case I still need to set height and width values in the img tag)

What I need to use if I want to provide different sizes for my images and webp format as well and leave the decision to the browser what to choose?

Can I provide webp image without picture and source tag? Can I use the picture method and still let the browser choose what image shown?

Not sure either why we need to choose the fallback with simple img src for the smallest image, in that case if someone enter with IE and a big screen then the image will be always pixeled. In those cases I'd prefer make some users wait a little longer than provide them with a low resolution image. Also.. having a low resolution image with the fallback option, not sure how influences in the individual image seo ranking.


回答1:


Your description looks like a common use case for responsive images. If you have for example an image that is shown at 50% width on large screens and at 100% width on viewports smaller than 900px, your HTML could look like this:

<picture>
    <source
        type="image/webp"
        sizes="(min-width: 900px) 50vw, 100vw"
        srcset="image-500.webp 500w, image-1000.webp 1000w, image-1500.webp 1500w"
    >
    <img
        sizes="(min-width: 900px) 50vw, 100vw"
        srcset="image-500.jpg 500w, image-1000.jpg 1000w, image-1500.jpg 1500w"
        src="image-1000.jpg"
    >
</picture>

This way browsers that support <picture> and webp images select one of the image-*.webp files, browsers that support srcset and sizes select one of the image-*.jpg files and all other browsers show the image-1000.jpg.

The most important part with this technique is to specify the sizes attribute correctly so browsers can make good decisions which image to load. You can find more information about it here: https://ericportis.com/posts/2014/srcset-sizes/

The image you want to display on “old” browsers can be freely selected via the src attribute. Or you “polyfill” the feature via JavaScript with tools like Picturefill or respimage.

You can omit the <picture> and <source> elements and do the type switch on the server side via HTTPs Accept header as an alternative.



来源:https://stackoverflow.com/questions/39321114/responsive-image-picture-vs-img-with-srcset-fallback-issue

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