Building and Sharing Custom Elements using Declarative Shadow DOM
A look at Web Components and templating approaches using Declarative Shadow DOM
--
Web components have seen a surge in adoption, changing the way we think about building and sharing reusable UI elements. In smaller organizations, you may find one or two teams that commit to using React, Svelte, or Vue.js for their rendering technology and build a library of shared components. But in large organizations, you most likely won’t have that luxury. This is where the web components standard thrives, offering a component model that can be used in any frontend stack. While building and sharing these components across various teams align well with standard patterns for developing, publishing, and integrating JavaScript components, they come with inherent challenges. Given their primary role as client-side solutions, developers often grapple with issues such as FOUC (Flash of Unstyled Content) or unexpected layout shifts during the initial page render.
Battling FOUC and Layout Shifts
When using custom elements, FOUC and layout shifts are significant concerns. These issues can harm your website’s core web vitals, potentially leading to reduced search ranking visibility. To counteract these effects, you can employ CSS features like the :defined pseudo selector. This selector lets you style custom elements according to their loading status. While this is effective in many cases, there may be times when you’d prefer to avoid these disruptions altogether, aiming for an immediate render of your custom element before its linked JavaScript loads.
Declarative Shadow DOM
Enter Declarative Shadow DOM, a browser technology that’s not an all-encompassing SSR (Server Side Rendering) solution for custom elements but can delegate the templating part of your element to the server in a technology-agnostic way.
This method leverages a template element with the shadowrootmode=”open” attribute. When encountered by the HTML parser, it creates a Shadow Root and populates it with the template content. The beauty of the Declarative Shadow DOM lies in its similarity to client-side-created Shadow DOM, but with a bonus: it supports streaming…