Misc Utilities / Light Style

Contents
  1. Problem
    1. Solution
      1. Example
        1 request, 2 KB (1 KB compressed)
        Module
        File size
        Compressed
        /src/util/LightStyleMixin.js
        1.95 KB
        0.67 KB

        Problem

        Shadow DOM has a non-negligible impact on browser performance. It might be better to avoid using Shadow DOM for custom elements which are used dozens of times in an app like buttons and list items.

        But how do you package the built-in styling for those custom elements? The LightStyleMixin explores one option while we wait for the W3C standard which allows us to do this natively.

        Solution

        Provide a lightweight mechanism to add styles to a custom element which dynamically injects them into the same scope as the element is used in.

        Example

        Red and bold

        <script type="module">
        import { LightStyleMixin } from '/src/util/LightStyleMixin.js';

        class StyledElement extends LightStyleMixin(HTMLElement) {
        static get styles() {
        return `
        :host {
        color: red;
        font-weight: bold;
        }
        `
        ;
        }
        }

        window.customElements.define('styled-element', StyledElement);
        </script>

        <styled-element>Red and bold</styled-element>