Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

Media Queries to load resource?

I am wanting to break apart my rather large CSS file into separate, specialised, stylesheets - one for mobile, tablet and desktop. The purpose being I want to reduce the amount of data being downloaded on mobile (why download 600kb css file containing mobile tablet and desktop styles when I can download a 40kb file just for mobile instead?).

Is there a way to use media queries to load only the required stylesheet?

I have tried:

@import url(mobile.css) (max-width:599px);
@import url(tablet.css) (min-width:600px);
@import url(desktop.css) (min-width:1200px);

and

<link rel='stylesheet' media='screen and (max-width: 599px)' href='mobile.css' />
<!-- and again for tablet and desktop -->

but in developer tools I can see that the browser downloads all three css files regardless of which technique I use.

Is it possible to load only the wanted resource using media queries?

I am aware of a JS approach using matchMedia but I am looking for a CSS only solution.

Edit

Please read the question - I want to load a specific stylesheet based on media query. ALL browsers download ALL stylesheets regardless of media query attribute, which defeats the point in having a mobile-only stylesheet! How do I download ONLY the stylesheet I want based on media query?

Upvotes: 1

Views: 1595

Answers (2)

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

If you make this, your site will not be responsive. Responsive said that design adapts to resolutions, not only devices, and when a desktop screen has a 600 px width you must to show tablet version, no? The best way to reduce the files is minifying all your css in one file in production version, and in dev version you have got all splitted css

Upvotes: 2

Mousey
Mousey

Reputation: 1865

Try doing it within the HTML, for example:

<link rel="stylesheet" media="only screen and (handheld)" href="example.css" />

source I can't see why this would not work with a (min-width: 1200px)` (for instance).

Normally though css for small screens would be very small, with the small screen using most of the styling in the desktop version, with a few elements hidden and some resized.

Upvotes: 0

Related Questions