I include 2 stylesheets in a page, one is the version for mobile that is alwys required. on larger screens i would like to load desktop.css in addition. So I link the desktop style so:
<link href="/css/desktop.css" rel="stylesheet" media="all and (min-width: 780px)" />
I thought that the browser would be clever enough to download desktop.css only on large screens. It loads it always however.
Is it possible to prevent the browser from downloading when the media query is not met?
No it is not possible. For media queries the resource is still downloaded (though often at lower priority) but not applied.
This has always been the case even with media=print
for example. The exact reasons aren’t clear to me, but there was a brief discussion in this issue, suggesting it broke too many sites - sites presumably that checked the media queries in the CSSOM for even when they didn’t match. That issue clarifies that link rel=“preload”
does honour the media query in terms of downloads but there is less risk of breakage there (preload is just an optimisation hint).
The fact that non-matching media queries are downloaded (but not render blocking) actually forms the basis of a bit of a hack to load CSS async with the following code:
<link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'">