1

i want to load/fetch style-mw-1024.css file when the device or browser is in width less than 1024.

<link rel="stylesheet" type="text/css" href="css/style.css" media="screen">
<link rel="stylesheet" type="text/css" media="screen and (max-width: 1024px)" href="css/style-mw-1024.css" />

But even when load in desktop greater than 1024 width, in network i am able to see style-mw-1024.css file is fetched.

How to prevent that file gets loaded in greater than 1024 width so that it loads only on media attribute conditions ?

1
  • 1
    It is always loaded, only applied when your media query is met (what would happen if someone resized their screen up and down if it was not always loaded - it would have to keep reloading it everytime you went in and out of the query). Why not just put the media queries at the end of your main stylesheet? One less http request so speed up your page. If you only want it to download when your media query is met, then you will need to dynamically load it with js, wouldn't recommend this though as you will get FOUC
    – Pete
    Mar 21, 2019 at 13:42

2 Answers 2

2

You cannot do that with the media attribute in markup. From my answer to another question:

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.

You can work around this by moving the media query to a JavaScript window.matchMedia() call and adding the stylesheet to your page when the media query is matched, but this means the stylesheet will require JavaScript to work.

1
  • 1
    Thanks for the clear explanation, and the work-around! It's a shame stylesheet loading works in this way though, as surely most users never actually resize the viewport (tablet orientation change is probably the only common scenario). If a mobile phone is downloading stylesheets for a viewport size it can never achieve, that seems wasteful to me! I'd rather have a FOUC for the 1% than slower loading for the 99% of visitors.
    – JoLoCo
    Sep 13, 2021 at 17:42
1

Implement a declarative fetch request on the rel="" attribute with a value of preload. Read Mozilla docs for a detailed explanation.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.