liveBook · Manning

Css-vars-ponyfill

As explained in Web Components in Action

css-vars-ponyfill is a client-side JavaScript library that processes CSS custom properties into CSS declarations supported by older browsers.

css-vars-ponyfill lets older browsers such as IE process CSS custom properties. It is a ponyfill rather than a drop-in browser patch: load it, then call cssVars(). section 12.5

Use it in three stages:

  • Install it with npm or load its browser script. section 12.5
  • Render any component markup and styles that contain custom properties. section 12.5
  • Call cssVars() afterward so the library processes style tags and swaps in declarations IE understands. section 12.5

Safe optional invocation

After setting innerHTML, check typeof cssVars !== 'undefined' before calling cssVars(). This lets component consumers include the ponyfill optionally without triggering an undefined-variable error. section 12.5

Listing 12.14. Adding the CSS vars ponyfill to allow existing CSS vars to work in IE
connectedCallback() {
   if (!this.initialized) {
       this.root.innerHTML = Template.render({ useShadowDOM:
         Slider.USE_SHADOWDOM_WHEN_AVAILABLE && this.attachShadow });
       this.dom = Template.mapDOM(this.root);
       if ( typeof cssVars !== 'undefined') {           #1
           cssVars();                                   #2
       }
       this.initialized = true;

       if (this.backgroundcolor) {
           this.setColor(this.backgroundcolor);
       }
       if (this.value) {
           this.refreshSlider(this.value);
       }
   }
}

Inspect the complete connectedCallback integration, including rendering, guarded detection, and invocation. section 12.5

How Web Components in Action covers it

How deep it goes
Explains installation, script loading, invocation timing, style processing, and guarded global detection, but not the rewriting algorithm.
Examples
Uses an npm installation, CDN script, and slider connectedCallback that renders styles before calling cssVars().
What it assumes
Assumes familiarity with client-side scripts, npm dependencies, CSS custom properties, and component lifecycle callbacks.
What you can do after
Apply it via npm or a browser script, then invoke cssVars() at the correct component-rendering point.
How it connects
Connects CSS custom properties with ponyfills, Web Components, connectedCallback, npm, and IE compatibility.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.