How do I tell srcset attribute to load NO images when viewport smaller than certain size

Ben Racicot picture Ben Racicot · Oct 26, 2014 · Viewed 10.3k times · Source

I'm having trouble understanding how to keep srcset from loading any images on screens < 768px.

I've tried the code below but the sizes attribute doesn't seem to do what you may think. Below loads 1024.jpg on all screen sizes:

<img 
  src="default.jpg"
  srcset="img/1024.jpg 1024w" 
  sizes="(min-width: 768px) 768px, 100vw"
/>

Or the picture element, if it would honor an empty srcset but it only "hints" to which image a browser should load.

Answer

alexander farkas picture alexander farkas · Mar 29, 2015

The other answer isn't really satisfying. In general with srcset you give the browser the choice to select an image candidate. While you can assume which image is taken on certain devices. You don't have any control. Each image in srcset can be taken.

So if you want to control, what is used or not used, you need to use the picture element.

Here are 3 examples. If the viewport is 768px or wider the 'img/1024.jpg' image is downloaded, otherwise a data uri or a broken img is selected.

<picture>
  <!--[if IE 9]><video style="display: none;"><![endif]-->
  <source srcset="img/1024.jpg" media="(min-width: 768px)">
  <!--[if IE 9]></video><![endif]-->
  <img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" alt="Image">
</picture>

<picture>
  <!--[if IE 9]><video style="display: none;"><![endif]-->
  <source srcset="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" media="(max-width: 768px)">
  <!--[if IE 9]></video><![endif]-->
  <img src="img/1024.jpg" alt="Image">
</picture>

<!-- you can also write (but this makes it invalid) -->

<picture>
  <!--[if IE 9]><video style="display: none;"><![endif]-->
  <source srcset="img/1024.jpg" media="(min-width: 768px)">
  <!--[if IE 9]></video><![endif]-->
  <img alt="Image">
</picture>

Although the first and the second code example are absolutely valid. There is currently some discussion to allow this by simply omitting the srcset (see code example 2). See this discussion here: https://github.com/ResponsiveImagesCG/picture-element/issues/243