Search code examples
cssmedia-queries

Is a CSS background image loaded on mobile when mobile media query uses a different image?


Say I have body{background: url(image1.jpg)} by default and I also have a media query for mobile (active when viewport width is less than 600px) which sets some image2.jpg image to the same body element.

On mobile, will image1.jpg still be loaded then replaced by the media query by image2.jpg?


Solution

  • No, only the mobile image is loaded. It's actually very simple to demonstrate this. Resize the snippet window to below 768px before running it, wait for the background to load, then resize it to fullscreen, you can see the desktop background is loaded anew:

    body{
      height: 100vh;
      background-image: url('https://static.pexels.com/photos/96918/pexels-photo-96918.jpeg');
      background-size: cover;
    }
    
    
    @media screen and (max-width: 748px){
      body{
        background-image: url('https://static.pexels.com/photos/27714/pexels-photo-27714.jpg');
      }
    }
    <div class="demo"></div>

    Since user @Johannes doesn't agree, I will give a more solid proof.

    This is before I expand the window: enter image description here

    And this is after: (the background is now white because the image has not finished loading) enter image description here