I've begun my first forays into using Web Components this month and there's things I like about them, but I admit that I've been befuddled by the Shadow DOM, which seems to be primarily a way to isolate my component, styles and all, from the rest of the website.
I imagine this is great for building component library to be used by many people across different sites, but for adding interactivity to one site, I *want* my components to share styles! A button is a button anywhere.
I thought maybe I just wasn't getting it. After all, what are Web Components other than a glorified replacement for the domready pattern if you're not gonna use the fancy shadow DOM? Maybe I shouldn't be using them after all!
I was pleased to discover a bunch of devs I admire had the same reaction—delighted by web components, unpersuaded by the shadow DOM. They build their web components using what they call the "light DOM" just the same old DOM that's always there.
So what *are* the advantages of web components (I guess I should really say just the "Custom Elements API" since that's the part I'm using) if you take away the shadow DOM?
1. It's obvious in the markup which elements are designed to be javascript enhanced. No more needing to add "js-" prefixed class names to make it clear what class names are for javascript alone to use. If you see a custom element with hyphens in the name, it's almost certainly JS-enhanced.
2. The custom element pattern is cleaner than the domready pattern and works more consistently. It ensures that no matter when your element gets added to the dom, the javascript enhancement gets run.
3. Because, unlike components in an SPA framework, web component inner HTML renders before javascript, there's a bit of a nudge to use HTML as much as you can to build your element and then layer javascript on top. Oh, wait, that's progressive enhancement!
I'm sure there's other advantages as well. Access to lifecycle methods and attributes seems useful. Being able to provide APIs directly on the elements for cross-element interaction may prove helpful. I haven't really used those yet.
One annoyance is that the <template> and <slot> elements don't seem to be useful unless you buy into the shadow DOM. I'd love to be able to do some language-native templating when building components up here in the light DOM!
Wow, this wasn't blog post length when I first started writing it, but now it is a blog post. Maybe I should copy it to my blog.
OK, I turned this into a blog post:
https://chromamine.com/2024/10/you-can-use-web-components-without-the-shadow-dom/