Doubt about loading images in CSS

Asked

Viewed 56 times

0

I would like to optimize the loading of images from my site according to the size of the device that accesses it.

My idea is to use media querys in css and depending on the device resolution load a worse quality image as background-image of a div.

Then I got the question: all the images referenced in a css file, for example: . Classe1 { background-image: url('image.png') }, are loaded automatically, or are only loaded if there is an element with a . Classe1 in my html?

1 answer

1


Depends on the browser.

Some browsers can locate all images, including those not used on the page.

This has a positive side, after all the desktop user can resize the window, for example, so the images are already cached.

Testing:

@media all and (min-width: 1024px) {
    .teste {
        background-image:url('http://lorempixel.com/output/abstract-q-c-200-200-1.jpg');
        width:200px;
        height:200px;
    }
}

@media all and (max-width: 1024px) {
    .teste {
        background-image:url('http://lorempixel.com/output/abstract-q-c-200-200-2.jpg');
        width:200px;
        height:200px;
    }
}

Upshot:

Used Chrome 52 in Windows 10: Chrome 52

You only got what is defined by @media all and (min-width: 1024px) {.

Used Microsoft Edge in Windows 10: Microsft Edge

Got all the images from both @media.

Used Firefox in Windows 10: Firefox

You only got what is defined by @media all and (min-width: 1024px) {.

Used Chrome (Mobile) 52 on Android 6.0.1 Chrome Mobile 52

You only got what is defined by @media all and (max-width: 1024px) {.

All situations the website was accessed in maximized window @media defined, except in Mobile, which is precisely where the other image should be displayed!

Completion:

Each browser works in a different way, although in general tend to respect what is defined by @media, at least in the most recent browsers!

These tests were done by me, so I have not tested in more browsers or in more situations. However some people have already done more complete tests and more situations, you can find more tests (mainly from old browsers), in https://timkadlec.com/2012/04/media-query-asset-downloading-results/.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.