HTML srcset Attribute Explained

The srcset and sizes attributes on img (or source) elements allow authors to define various image resources and “hints” that assist a user agent to determine the most appropriate image source to display (e.g. high-resolution displays, small monitors, etc).

Typically, when you embed an image into a page, you only define one “source”, in the form of the src attribute, like so:< img src=”/images/whatever.jpg” alt=”whatever”>

The srcset attribute allows you to add other versions of the image, set the screen width at which those images are meant to appear, and let the browser make the decisions. This means that the user’s device only downloads the right image for their screen size.

You would set it up like so:< img src=”/images/whatever-small.jpg” srcset=”whatever-medium.jpg 1000w, whatever-large.jpg 2000w” alt=”whatever”>

  • You’re letting the browser do the math. Picking the right image for the right screen size can be tricky, and if you’re using a lot of images, you probably don’t want to bother.
  • You’re saving bandwidth. This means lower hosting costs for you, and lower data costs for mobile users.
  • Partial browser support. In fact, this is the second-best-supported option on the list.

Cons

It’s only partial browser support. To make it work in older browsers (including some mobile browsers), you’ll need to use a bit of JavaScript called a polyfill.

Two such polyfills are srcset-polyfill, and picturefill. Incidentally, picturefill also provides browser support for the <picture> element, which is coming up next.

In the end, using the srcset attribute on a single <img> tag is probably the option that people will use most in the future. It just makes sense, when most of us will simply be using several differently-size versions of the same image, in order to save bandwidth.

Read more: https://www.webdesign.org/responsive-images-why-it-s-a-must-and-4-ways-to-have-it-done.22532.html#ixzz5gzTdKWo5

Browser Support: https://caniuse.com/#search=srcset