Search code examples
imagecssresponsive-designmedia-queries

Using media queries to control image downloads


If I create a container and want to set a background image based on media queries, why does the browser (Firefox, Chrome) download the medium sized image, if the large one has already been downloaded? That seems totally against the point (i.e. saving bandwidth).

HTML

<div id="background"></div>

CSS

#background {
    width: 100%;
    height: 400px;
    background-image: url(/content/images/2016/04/airport-small.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
}

@media (min-width: 500px) {
  #background {
    background: url(/content/images/2016/04/airport-medium.jpg);
  }
}
@media (min-width: 800px) {
  #background {
    background: url(/content/images/2016/04/airport-large.jpg);
  }
}

If I load a page the browser downloads the -large.jpg, in this setup. If I resize the screen (below 800px), the browser downloads and renders the -medium.jpg, and so on.

How can I prevent this?


Solution

  • I think the main cause of the conflict here is your assumption that media queries were implemented to save bandwidth. They were implemented to display different things at different sizes, that's all. The fact you've chosen to display the same image at a different size was simply how you decided to utilize them, and media queries are just faithfully doing what they promised to do all along: Show the user what you told it to show the user.

    I'd recommend evaluating whether this is really a worthy investment in time and code (keeping in mind that most users won't resize a window or rotate a mobile device, and those who do probably wouldn't be put off by a flash-and-reload). If you decide to do it, it won't be through only CSS. Your best bet will to research JavaScript methods to do this, such as adding a class loaded-large to the body tag onload, and then writing a CSS rule for smaller images only to load when the body tag does not have class='loaded-large'.

    Hope this helps.