7
votes

I'm using Bootstrap with Responsive Images. I want to optimize load times by offering multiple image sizes to browsers. According to this article, a plain approach with srcset like this is good for letting the browser pick the optimal image size:

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="yah">

My problem is that combining this with the Bootstrap img-responsive class, a large size picture gets loaded even when only a small one is needed.

Code example here: Bootply . Use Chrome for testing, it has built-in support for srcset support! (Some other browsers would need picturefill.js to recognize it.)

If you copy the source of the image (or look in Chrome Developer Tools in the Network tab), you can see that the 750 width version gets loaded, and resized to a small image, even though there are smaller versions that would be optimal to use. (The same thing happens in IE and Firefox if the picturefill JS is loaded to support img srcset.)

What am I doing wrong?

1

1 Answers

9
votes

You need to use the sizes attribute to tell the browser which width the image will have in your design, otherwise it defaults to 100vw (full viewport).

<img sizes="(max-width: 480px) calc(100vw - 10px), 480px" src="small.jpg" srcset="small.jpg 600w, medium.jpg 1000w, large.jpg 2000w" alt="yah" />

In case you can set the width in CSS, you can also use lazySizes to automatically calculate the sizes for you.

With lazySizes:

<img data-sizes="auto" class="lazyload" data-srcset="small.jpg 600w, medium.jpg 1000w, large.jpg 2000w" alt="yah" />