Search code examples
htmlcssmedia-queries

Will `not` media query save resources when importing css?


Current I have the following set in the css:

<style>
        @import url("default.css") screen;
        @import url("light.css") screen and (prefers-color-scheme: light);
</style>

I want the default.css be loaded when
i) user is in dark mode;
ii) user did not specify any colour theme preferences; or
iii) user is visiting with a browser that does not support prefers-colour-scheme query.
should I then change the first import rule to @import url("default.css") screen not (prefers-color-scheme: light); to save resources, and will this actually save resources?

Appreciate for your answer.


Solution

  • Whether or not it will save resources is browser dependent.

    From what I have observed, the media query is evaluated at runtime after actually importing the file. You can easily check in the network tabs of the debugging tools if the file is being downloaded or not. This has the most impacts client-side.

    opinionated: For the content of the files, you should make your default.css agnostic of the colouring scheme (more about common stuff) and have a light.css with only changes that apply, and then have another dark.css for the "non-light" theme.

    The less you override rules, the better (for your own sake). Although, unless you have millions of rules, the impact of overriding a rule or adding more rules is close to negligible and is/should be optimized by the browser.