Search code examples
javascriptcsscss-variables

Will my js script break by setting css --variables on legacy browsers?


I want to start using css --variables. For legacy browsers, the css fallback is to declare a legacy rule first, and that's fine. But then I will manipulate them via javascript. So, is it going to break the script and throw some errors in legacy browsers? I ask because I currently can't test on legacy, so I can't see by myself.

I mean, if I do something like this:

elem.style.setProperty('--tx', `10px`);

What will happen in legacy browsers? Just nothing (--tx will silently not update and the program will go on) or, throw an error and break the script?


Solution

  • According to the specification, setProperty() can throw a DOMException under these conditions:

    SYNTAX_ERR: Raised if the specified value has a syntax error and is unparsable.

    NO_MODIFICATION_ALLOWED_ERR: Raised if this declaration is readonly or the property is readonly.

    If you want to be safe, wrap the call in a try...catch or a condition based on Modernizr.customproperties to ensure that the call is either caught if it throws an exception in legacy browsers, or is only called if the browser supports it.

    I also suggest you not use template literals or transpile it to ES5 using Babel.