Media Queries and Bandwidth


I just read a blog post that stated that media Queries were not a good idea because:

your entire stylesheet, with resources, images, the works – for all viewports - is loaded, before the @media stuff is parsed by the browser.

This isn’t entirely true. Although all of the CSS will be downloaded, background-images will not be.

Browsers are smart enough to only load the required assets. To show this I created a very simple sample.

    <style>
        div
        {
            width: 800px;
            height: 400px;
        }
        
        @media screen and (min-width: 0px) and (max-width: 750px)
        {
            div
            {
                width: 400px;
                height: 600px;
                background-image: url('smaller.png');
            }
        }
        
        @media screen and (min-width: 751px)
        {
            div
            {               
                width: 800px;
                height: 400px;
                background-image: url('big.png');
            }
        }
    </style>

If the view port is bigger than 751px then the big image is shown. If the view port is smaller than 750 the smaller image is shown.

I then open up IE9 press F12 to open the developer tools and switch to the network tab. In the network tab I hit the button “Start Capturing” I then navigate to the page. This is what I see:

image

You will notice that only the big.png file is loaded. As I make the window smaller than 750px the other image switches in and is loaded.

image

You can read more about what is and isn’t downloaded by Media Queries in this article, which also covers the issue display:none not stopping images downloading.

Comments (0)

Skip to main content