Search code examples
htmlcssmedia-queries

Eliminate style loading using media queries


I try to speed up initial loading by eliminating unnecessary downloading. I split styles in to portrait and landscape css. And want to load only one style based on media queries. But is seems they are loading together.

<body>
  <link rel="stylesheet" type="text/css" href="style-p.css" media="(orientation: portrait)" />
  <link rel="stylesheet" type="text/css" href="style-l.css" media="(orientation: landscape)" />
</body>

enter image description here


Solution

  • The purpose of media attribute in a <link> tag is to decide when the resource applies, not if it loads. It always loads.


    So, simply put, what you seem to want is not possible without JavaScript. There is nothing in the current CSS Editor's Draft to indicate it should or will ever be possible using clean HTML + CSS.

    If you think about it, this makes a lot of sense. All it takes to flip your device from landscape to portrait is a pet on the back by an enthusiastic colleague. And it would be impossible to provide a decent user experience if you had to wait for a resource to load before the layout change was applied.

    The closest the spec gets to the subject is in:

    User agents must re-evaluate media queries in response to changes in the user environment that they’re aware of, for example if the device is tiled from landscape to portrait orientation, and change the behavior of any constructs dependent on those media queries accordingly.

    But there's an important note on this: most modern browsers made the following (smart) choice: they load <link> resources with media attributes evaluating to false as non-blocking to reduce the time needed to initially render the page to the user.
    One of the first articles to go viral on the subject was written by Keith Clark. You might also find Taylor Hunt's follow up interesting.


    If you are still interested in loading stylesheets based on @media query conditions, you will need to load them using JavaScript. For performant detection of @media queries in JavaScript, I recommend enquire.js.