Load stylesheet based on support for CSS custom properties?

59 Views Asked by At

<link> supports a media attribute for conditionally loading CSS. Is there a media query that can approximate support for CSS variables? Somehow like this. It'd be okay if some browsers that support CSS vars get the legacy too but not the opposite. It'd just be important that exactly one stylesheet load.

<link rel="stylesheet" href="legacy.css" media="(???)">
<link rel="stylesheet" href="modern.css" media="(???)">
1

There are 1 best solutions below

0
chriskirknielsen On

I don't believe you can do that in a media query, as far as I know. However, you can test for support in JavaScript and inject your CSS accordingly.

var newLink = document.createElement('link');
newLink.rel = 'stylesheet';

if (window.CSS.supports('--modern-var', 0)) {
    newLink.src = 'modern.css';
}
else {
    newLink.src = 'legacy.css';
}

document.head.appendChild(newLink);