Search code examples
htmlcssmedia-queries

Are LINKed stylesheets out of the specified media even loaded?


I want the stylesheets out of the defined device width defined in a LINK tag not to be even loaded if it doesn't apply.

I could import it from the main stylesheet (for handheld devices) by placing the import line at the bottom, only if I knew that file would be imported AFTER the rest of the css has been parsed, including images.

So what is the behavior of the link tag when media properties are specified? Are they not used BUT loaded anyway? Are they NOT loaded at all? (what I wish)

Thanks.


Solution

  • A browser can't assume that it will never match a media query, so it has to load the stylesheet in case it ever does match the media query and has to use the stylesheet as a result. This eliminates any network latency associated with lazy-loading that would cause a problem similar to FOUC, where the content doesn't look right for a fraction of a second (or, if the connection gets really spotty, several seconds) as the browser waits for the stylesheet to be loaded before it can be used.

    Note that the same applies with @import statements. The spec however does not require a browser to either load a stylesheet conditionally, or always load it. This is implementation-dependent. As far as I have seen though, all browsers will load a stylesheet anyway regardless of media queries.

    You cannot have an @import statement anywhere other than the beginning of a stylesheet before any rulesets anyway.