Is there a way to pollyfill a custom CSS property for ie11 with JavaScript? I was thinking on load, check if browser supports custom properties and if not do some kind of find and replace on the properties.
Is this possible with JavaScript or some library?
Thanks
Have a look at this (my) Custom-Properties-Polyfill:
https://github.com/nuxodin/ie11CustomProperties
The script makes use of the fact that IE has minimal custom properties support where properties can be defined and read out with the cascade in mind..myEl {-ie-test:'aaa'} // only one dash allowed "-"
then read it in javascript:getComputedStyle( querySelector('.myEl') )['-ie-test']
From the README:
Features
- handles dynamic added html-content
- handles dynamic added , -elements
- chaining
--bar:var(--foo)
- fallback
var(--color, blue)
- :focus, :target, :hover
- js-integration:
style.setProperty('--x','y')
style.getPropertyValue('--x')
getComputedStyle(el).getPropertyValue('--inherited')
- Inline styles:
<div ie-style="--color:blue"...
- cascade works
- inheritance works
- under 3k (min+gzip) and dependency-free
https://rawcdn.githack.com/nuxodin/ie11CustomProperties/b851ec2b6b8e336a78857b570d9c12a8526c9a91/test.html
You didn't mention how you're bundling your JavaScript, but yes, it's possible. For example, PostCSS has a plugin, which polyfills this feature.
The usage depends on how you're bundling your script files. With Webpack, for example, you'd define this plugin in your postcss config or import it as a plugin under your webpack config:
// webpack.config.js: module.exports = { module: { rules: [ { test: /\.css$/, use: ["style-loader", "css-loader", "postcss-loader"] } ] } } // postcss.config.js module.exports = { plugins: [ require('postcss-custom-properties'), require('autoprefixer'), // any other PostCSS plugins ] }
The plugin also has an example for programmatic usage (as a separate node script):
// dependencies var fs = require('fs') var postcss = require('postcss') var customProperties = require('postcss-custom-properties') // css to be processed var css = fs.readFileSync('input.css', 'utf8') // process css using postcss-custom-properties var output = postcss() .use(customProperties()) .process(css) .css
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With