Search code examples
cssmedia-queries

media queries, images, and load times


I've got 3 different images that I want to display for 3 different display ports. My question is this. If someone on a cellphone loads up my website, will their device have to download all 3 images at load? Will the device prioritize the image that pertains to their viewport and download that one first?

Essentially, I don't want a user's load time of the page (time to full paint) to be impacted by specifying different bgimages for different viewports.

.bgpattern {
  background-image: url(../images/bg1.jpg);
}

@media (max-width: 1200px) {
  .bgpattern {
     background-image: url(../images/bg2.jpg);
  }
}

@media (max-width: 767px) {
  .bgpattern {
     background-image: url(../images/bg3.jpg);
  }
}

Solution

  • It is browser dependent. Chrome and Safari wil only download the applicable background image.

    You can test that behaviour with the Chrome developer tools:

    1. Open the Chrome developer tools (F12)
    2. In Elements, click Toggle Device Toolbar
    3. Set your viewport
    4. Open the Network tab
    5. Reload your page.
    6. Check which images were loaded which images were not

    This is better explained in this blog post: https://web.dev/optimize-css-background-images-with-media-queries/