Tagged “shadowdom”
Web Components with Declarative Shadow DOM via Lit and Eleventy
Here’s a new development in the Web Components story, and one that may have positive implications for resilience, performance and progressive enhancement.
Declarative Shadow DOM is a new way to implement and use Shadow DOM directly in HTML rather than by constructing a shadow root in JavaScript.
But some people including Chris Coyier and Brad Frost) reckon that writing that looks horrible. Brad said:
Declarative Shadow DOM always looked gross to me and I felt it almost defeats the purpose of web components.
And Chris added:
the server-side rendering story for Web Components, Declarative Shadow DOM, doesn’t feel very nice to me if you have to do it manually.
However Lit, a library which makes working with Web Components easier, are now providing ways to make this easier when Lit is used with Eleventy.
With tools like this (especially this @lit-labs/ssr project), we can have our cake and eat it too: use web components in a dev-friendly way, and then have the machines do the heavy lifting to convert that into a grosser-yet-progressive-enhancement-enabled syntax that ships to the user.
using JavaScript frameworks in an entirely-client-side rendered way isn’t nearly as good for anything (users, SEO, performance, accessibility, etc) as server-side rendering (the effects of hydration are still debatable, but I view as largely worth it) … [but] the server-side rendering story for Web Components, Declarative Shadow DOM, doesn’t feel very nice to me if you have to do it manually. So… don’t do it manually! Let Eleventy do it!
As an additional footnote, perhaps we can make frameworks other than Eleventy (such as Rails) create server-rendered custom elements with Declarative Shadow DOM in a similar way. One to explore.
My first Web Component: a disclosure widget
After a couple of years of reading about web components (and a lot of head-scratching), I’ve finally got around to properly creating one… or at least a rough first draft!
Check out disclosure-widget on codepen.
See also my pen which imports and consumes the component.
Caveats and to-dos:
- I haven’t yet tried writing tests for a web component
- I should find out how to refer to the custom element name in JavaScript without repeating it
- I should look into whether
observedAttributes
andattributeChangedCallback
are more appropriate than the more typical event listeners I used
References
I found Eric Bidelman’s article Custom Elements v1: Reusable Web Components pretty handy. In particular it taught me how to create a <template>
including a <slot>
to automatically ringfence the Light DOM content, and then to attach that template to the Shadow DOM to achieve my enhanced component.
See all tags.