简体   繁体   中英

Load stylesheet based on support for CSS custom properties?

<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="(???)">

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM