It's wrong - both that it's general "current advice", and the advice itself when it does pop up.
Yes, there are some people who say to build web components without shadow DOM, but I'm convinced they're only building leaf nodes so they don't need composition with slots. As soon as they try to build any kind of container element they hit big problems.
In a parallel discussion happening on Mastodon, someone says:
> People coming from React-land can have a hard time reasoning about the difference between a custom element and a template render function and when best to use each
> This abuse of the component system can indeed lead to a massive explosion in nodes on a page and the performance tanks because of that
I know I certainly have that hard time deciding when I need a custom element and when a render function.
> As soon as they try to build any kind of container element they hit big problems.
That's not true. Web components that render nothing will contain only their children as nodes, that's good enough for a good amount of container use cases.
Web Components Community Group: 2022. You are one of the authors:
--- start quote ---
It's worth noting that many of these pain points are directly related to Shadow DOM's encapsulation. While there are many benefits to some types of widely shared components to strong encapsulation, the friction of strong encapsulation has prevented most developers from adopting Shadow DOM, to the point of there being alternate proposals for style scoping that don't use Shadow DOM.
...
Selection does not work across or within shadow roots. This makes fully-featured rich-text editors impossible to implement with web components. Some of the web's most popular editors have issues that are blocked on this functionality
...
Shadow boundaries prevent content on either side of the boundary from referencing each other via ID references. ID references being the basis of the majority of the accessibility patters outlines by aria attributes, this causes a major issue in developing accessible content with shadow DOM.
--- end quote ---
Those are just the tip of the iceberg as these are very explicitly stated in the doc.
Then there's the issues of shifting the responsibility to both developers and consumers to handle Shadow DOM correctly.
Styling/themeing is still pain despite several different specs like shadow parts.
Shadow DOM is a kind of retcon for the web. As I’ve written in the past, shadow DOM upends a lot of developer expectations and invalidates many tried-and-true techniques that worked fine in the pre-shadow DOM world.
Perhaps I care about the direction in which the web is pushed by a very small number of people incapable of seeing beyond their solutions and incapable of admitting their own mistakes.
At no point have I ever gotten the impression that you are even remotely open to seeing other points of view so it’s a bit hard to take the moralistic tone of the brave defender of the web part seriously. I think you just want to yell at people.
Web Components have been in development for 14 years. If you think this is the first discussion of web components, you clearly haven't been paying attention.
All there is to say was said years ago. Today it should be enough to know that, for example, "form associated custom elements cannot be a submit button" issue was opened 6 years ago, in 2019: https://github.com/WICG/webcomponents/issues/814
Imagine if any web framework had issues like that.
That doesn't even begin to cover things like "now every useful spec has to be acutely aware of Shadow DOM shenanigans" which delayed any number of specs like scoped CSS etc
It’s just like an LLM stuck on a loop. It’s just years and years of making the exact same comments, not responding to any counter arguments and then demanding that people take you seriously.
The great thing about web components is that you can build them however works best for you.
Native web component APIs don't have the DX that many people expect though, because they are so low-level. Lit provides just that declarative reactivity on top.
Hi! Not really a question, but just an appreciation message. I haven't used the full "Lit" package a lot, but "lit-html" is incredibly useful.
I use it in almost all my personal websites. And when I don't use it, I end up reinventing half of it and realize I should have used it from the start. This command is in most of my projects:
I've never felt I'm using a framework or anything that deviates from Vanilla JS and valid HTML, which is why using it hardly causes any more cognitive load than using regular string templates and JavaScript functions. Which is something that I can't say about other frontend tools.
Another thing I like from Lit is that with the CDN bundle, it's straightforward to experiment and use all the features without needing a build step.
Lots of comments in here are about shadow DOM, so let me give my take in one place:
Yes, Lit uses shadow DOM by default (for good reasons, I think!) and yes you can turn it off component-by-component, but that does bring some challenges.
Shadow DOM is most fundamentally just a private branch of the DOM tree for a component's internal DOM details.
Frameworks have this implicitly with DOM defined in a component's template vs passed as children. But that distinction isn't visible to other code, the browser, and CSS. This is both good and bad.
The biggest thing this separate tree gives us is the ability to tell what nodes are "children" - those are the light DOM children. Once you can separate children from internals, you can build slots. Slots are holes in the internals that children get rendered into.
Without something like shadow DOM you can't have slots. And without slots you don't have interoperable composition and you don't have viable container elements. You need some way to place children in an element that isn't confused with the element's own DOM.
So to me, before encapsulation and style scoping, interoperable composition is the most important feature, and that's really why Lit defaults to shadow DOM on. Without it we'd need some special `.children` property and Lit's component composition suddenly wouldn't be compatible with everyone else.
But the style encapsulation is often a major pain for developers, especially if they're trying to integrate web components into an existing system with whole-page stylesheets. It's a big blocker to a lot of design systems porting to web components.
That's one reason I proposed something called "Open Styleable Shadow Roots"[1] which would let styles from outer scopes cascade into a shadow root - a way to break open style encapsulation but keep slots. It's been hard convincing browser vendors that this is needed, but I'm holding out hope that it makes progress soon.
Nice to see you here and THANK YOU for the amazing tool that is Lit. It's everything you want from a framework without a framework getting in your way.
I'm sold and build all my work and personal apps with it and have for many years. I wrote this article about why in 2022:
Any whispers of something like lit being made part of the webcomponents standard?
Web components are nice because they're browser-native, but they don't support reactivity, which in hindisight, is a massive oversight, issue, whatever you want to call it - it's hindered adoption.
Lit is nice because there's a very straightforward progression from web components.
Lit has always been designed partially as a prototype for where web component standards could go in the future. That's a big reason Lit is fairly conservative and un-opinionated. It doesn't try to undo or paper-over any of the DOM APIs, but add to them instead.
There is a proposal in TC39 for native signals, which I think would make a huge dent towards library-less reactivity.
I'm also working on a proposal for native reactive templating which would more-or-less obsolete lit-html. I wrote about the idea some on my blog:
I hope there can be ways without JS to populate templates with data - autoloaded from sources. This would tremendously increase the number of JS free web-sites. Also wish the web-components standard did not mandate the use of JS. It should be possible to define simple web-components (HTML+CS) declaratively and have this officially supported in standard and implementation
I think we're stuck today in a little bit of a rut of extensibility. We wind up leaning on JavaScript to get things, because it is the Turning complete language in our environment. It is the only thing that can give us an answer when CSS and HTML fail us. So we wind up piling ourselves into the JavaScript boat. We keep piling into the JavaScript boat.
Bruce yesterday brought up the great example of an empty body tag, and sort of this pathological case of piling yourself into the JavaScript boat, where you wind up then having to go recreate all of the stuff that the browser was going to do more or less for you if you'd sent markup down the wire in order to get back to the same value that was going to be provided to you if you'd done it in markup. But you did it for a good reason. Gmail has an empty body tag, not because it's stupid. Gmail does that because that's how you can actually deliver the functionality of Gmail in a way that's both meaningful and reliable and maintainable. You wind up putting all of your bets, all of your eggs, into the JavaScript basket.
....
They're the sorts of things that you use when the semantic that you're trying to express is so far away from what HTML natively has a semantic for, that you're willing to go and be completely self served for it. Taking on for yourself accessibility, UI, UX, internationalization, localization, performance, theme ability; all of this stuff is mostly taken care of for you by HTML.
--- end quote ---
14 years later, web components depend on JS to:
- participate in forms
- solve accessibility issues (not yet, but coming through a yet another JS-only standard)
- CSS modules and other imports that are moved entirely into JS
etc. etc.
-----
Slight off topic. From the same talk:
--- start quote ---
Now, we can do some of that today. We can go and look at the top million pages and figure out which JavaScript library that they're using, which features are being most heavily used, we can put those things in DOM. But is that the right place for them? It's a hard thing to figure out.
--- end quote ---
I wish they spent time figuring that out. We wouldn't have to wait a few decades for https://open-ui.org to slowly make its way into the browsers.
The current draft is based on design input from the authors/maintainers of Angular, Bubble, Ember, FAST, MobX, Preact, Qwik, RxJS, Solid, Starbeam, Svelte, Vue, Wiz, and more…
I think web components already compete extremely well for application development, and you see very complex apps built with Lit out there: Photoshop, Firefox, Chrome OS, Chrome DevTools.
Apps are well served because they have more control about how components are used: they can import the same shared styles into every component, take are to not double-register elements, etc.
But I think there are some important standards still missing that would open things up even more in the design system and standalone components side:
- Scoped custom element registries. This moves away from a single global namespace of tag names. Seems like it's about to ship in Safari. Chrome next.
- Open styleable shadow roots. Would allow page styles to flow into shadow roots. This would make building components for use with existing stylesheets easier.
- CSS Modules. Import CSS into JS. Shipping in Chrome. About to land in Firefox.
- ARIA reference target: make idref-based reference work across shadow roots
What people using web components want is to get rid of shadowDOM and not feel like they are deviating from the correct path. shadowDOM sucks, stop trying to convince the world that we are using it wrong. shadowDOM is the whole reason web components did not become mainstream (yet?).
Nothing in Web Components is forcing you to use ShadowDOM. Lit also allows you to make components without ShadowDOM if you prefer, because there are certainly cases where it can be necessary to do so (like for ARIA reference id-matching). For full single application development, it can feel like it gets in the way a lot, and you can make a good argument to use components without ShadowDOM in those contexts too.
All frontend "frameworks" do have some sort of solution to scope CSS to individual components, and without a similar solution, a native component system would not be viable. The implementation has its quirks, but it is a core capability that is necessary for some use cases. For third-party widgets or cross-application components like design systems, the ability to isolate your component from the site it is embedded in is very useful.
Think of shadowDOM as the web component alternative to scoped styles in Vue components (as an example). You don't have to use it, but it would be incredibly inconvenient if it wasn't included in the framework.
> Nothing in Web Components is forcing you to use ShadowDOM
Yes. There is just one thing forcing someone to use shadowDOM: slots. You can't use slots without shadowDOM or at least use something like this.children to capture the content inside the <custom-element></custom-element>.
It's not possible to make slots work without a separate tree like shadow DOM. The browser can't tell what the container for a slot is vs what content should project into it.
I disagree completely. Shadow DOM is a huge help and when combined with per-component CSS using the :host() and nesting pattern, makes for very small CSS files and very short CSS class names. In other words, as far away from Tailwind as you can get.
It's also possible to import shared CSS in a base class and add it with super.styles() so you don't lose anything.
You don't want to enable portable components all the time. If most of the components you use to create your app is made by yourself, those boundaries are annoying, not helpful.
Please do not refer to CSS type imports in JS as CSS Modules.
CSS Modules has an established meaning for over a decade, one that is still relevant today. The CSS type imports are very different, and arguably worse.
Call them CSSStyleSheet imports of you need a name suggestion.
Another pain in the ass is the fact web components are registered globally. Good luck marrying this with npm dependency hell where two transitive dependencies both import a button.
The good part of react and friends is it's just javascript and the class is imported and referenced normally, not with a weak string-binding-through-registry kind of way.
Now add types to the mix and shadow dom and it brings constant problems without any upside.
What I wonder is whether there are any developments related to Lit regarding server-side rendering (SSR). This is one of the reasons I'm experimenting with Svelte now. To me Lit was taking away frustrations with the inefficiencies of React. But for me Svelte seems to fill that gap too, and it also has SSR, among other niceties. But I do like the philosophy of Lit & Web Components. Sometimes I think a framework that would be like Svelte but uses Lit under the hood would seem like the best of both worlds.
I can't find clear information about how re-rendering and stateful third-party components interact.
Let's say I have a stateful data table web component that I use in the template. Is it going to be re-created every time the template is re-rendered (loosing its internal state)?
Lit's just a JavaScript library published as standard modules, so it doesn't require a bundler. Using Lit efficiently is the same as using any other library.
HTTP/3, import maps, and HTML preloads can make unbundled app deployment almost reasonable in some cases. You'd still miss out on minification and better compression form a bundle. Shared compression dictionaries will make this better though.
You have a very large axe to grind against web components and Lit, and you show up just about everywhere to make the same comments, but I'll play along anyway:
Yes, Lit templates give some special meaning to attribute names with a few prefixes. No, it's not "HTML-like". It's valid HTML. Not that it matters much. You bring this up all the time but I'm not sure what the actual criticism is. Developers seem to understand the small syntax carve-out just fine.
No, there are no custom JavaScript rules. Templates have some rules. I'm not sure why they wouldn't? In general you can't make things like tag and attribute names dynamic because you can't change them in HTML. You can actually write the template you show with what we call static templates though.
`classMap()` is a template directive. It has some rules about how it's used in templates, just like other JS functions can have rules about how their used. I'm not sure what makes that not a function.
But to your main point: Lit is not like React because it's not a framework. Lit helps you make custom elements - it's an implementation detail of some web components. Everything else about those elements: how you instantiate them, style them, where they work, etc., is all defined by the HTML and DOM standards. React is a framework, and defines its own rules about how its components work.
Time to put the nail in that coffin! I use a static template to select and return components dynamically. It's a key aspect of my own internal "framework," made with Lit.
I love that I get to choose how everything works. I have custom systems for routing, styling, signals, API interactions. I control who gets passed what and when. It makes the app feel light, responsive, and -- most importantly, it fits in my head and I understand how it's put together because I chose it, not because I learned it from someone.
> You have a very large axe to grind against web components and Lit
Yes, yes I do. Because Web Components are almost 15 years now, and they still struggle with the most basic of things. How's that abandoned roadmap going? https://w3c.github.io/webcomponents-cg/2022.html
> No, there are no custom JavaScript rules. Templates have some rules.
That is "here are regular JS functions. However, you cannot use them as regular JS functions in these specific contexts". Reminds me of certain very specific rules about specific functions in specific contexts in some other framework. Can't put my finger on it.
> I'm not sure what makes that not a function.
I never said it doesn't make it a function.
> But to your main point: Lit is not like React because it's not a framework.
Yeah, React wasn't a framework either, but just a library. Everything about DOM elements that React produces, how you instantiate them, style them, where they work etc. is all defined by the HTML and DOM standards.
But then React grew in the number of features, and can no longer be called a library even though still the only thing it does is output some DOM nodes.
I guess you'll insist on Lit being "just a library" even after it adds a ton of other functionality all other frameworks already have or are moving towards.
> I'm not sure what the actual criticism is
The criticism is usual: Lit is rapidly absorbing all the features from all the other frameworks and becoming a framework itself while many of its developers and proponents can't stop shitting all over other frameworks.
I'm not sure how those links support your "lit proponents shit on other JavaScript libraries/frameworks", which was my complain about your post, or if that would even warrant as an excuse for you personally being an ass to the lit's maintainer directly.
Web Components is a pretty niche technology and as such it really appeals to some people, and it doesn't appeal to others, and that's okay. You don't have to like it, it isn't meant to be a good fit for everyone. But for some people it might fit really well with their requirements, and they probably have legitimate reasons for that.
If I understand correctly, your criticism is that the people for whom Web Components is a good fit are publicly discussing the reasons why they prefer it over other solutions?
The main problem is that for a "niche technology" it sure infects too many standards, requires an insane amount of new standards and makes supporting things needlessly complicated.
There are some good parts in the ~30 standards they require, but instead of just the good parts you get the whole horse, and the cart it's attached to, and the cargo in the cart.
> your criticism is that the people for whom Web Components is a good fit are publicly discussing the reasons why they prefer it over other solutions?
Ha this guy again, I recognize you too. I also don't understand your obsession with trolling on Lit and Web Components. You keep coming with the same arguments. And always very emotional. I get the feeling that it is something personal that you have against Lit / Web Components. And you're clearly a hater, and haters are gonna hate regardless of whatever happens.
I do wonder, why are you on this crusade? Are you afraid that people are at some point gonna be persuaded by Lit / Web Components, and that you need to be there to prevent that from happening?
By what I understood, I would expect him to use web components a lot even though he dislikes a few things, otherwise that would be really weird and a waste of life time.
Decorators are the only way to metaprogram over class fields in JS. Otherwise they're not even detectable on the prototype.
We use them to make fields reactive mostly, and I love how declarative they are. But we use them sparingly. I personally don't love how some libraries try to put a lot of things into decorators that could have been standard class features, like a static field or a method.
We also put a lot of effort into making all of our documentation and playground samples on lit.dev available in both JavaScript and TypeScript with decorators. There's a switch that will change everything on the site from JS to TS globally.
There really is no way to metaprogram against class fields except with decorators.
Class fields aren't on the prototype. They're essentially Object.defineProperty() calls that occur right after the super() call of a constructor. You can't get at them at all from the class declaration.
I know more than one way to do something is sometimes a downside, but we have a large audience an a huge portion of it wants to use TypeScript and declarators, and another huge portion of it wants to use vanilla JavaScript. We factored things to give the best DX we could to each group with relatively little cost to us.
As for why metaprogramming, we want a component to update when it's state is changed. Like plain web components, Lit uses classes.
So here, we want setting `el.name` to cause the component to re-render:
class MyElement extends LitElement {
name = 'World';
render() {
return html`<h1>Hello ${this.name}</h1>`
}
}
We do that by replacing `name` with a getter/setter pair where the setter schedules an update of the instance. Without decorators, there's no way to see that `name` even exists, much less replace it.
Decorators actually do the replacement for us, we just have to build the thing to replace it with:
class MyElement extends LitElement {
@property() accessor name = 'World';
render() {
return html`<h1>Hello ${this.name}</h1>`
}
}
I skimmed through your blog posts, and the WICG proposal, and my main objection to it is making it depend on JavaScript.
There are plenty of ways HTML templating can be done already using JavaScript. The simplest approach of using tagged template literals, as you mention, doesn't even require external dependencies.
The problem with this approach is that it makes JavaScript a requirement for all but static sites, and those doing templating on the server. This shouldn't be the case.
The web as a platform should be flexible, and provide tools to build maintainable web sites and applications without forcing developers and users to depend on a specific runtime. JS should be an optional dependency, just like CSS is today. Even HTML should be optional, as Web Assembly gains traction, and the web browser becomes a software delivery platform.
Furthermore, making what should be a core HTML feature depend on JS is a colossal violation of separation of concerns. HTML modules should be a standalone feature, and we should be able to define a tree of HTML modules, import modules, reuse them, and so on. That should be the core groundwork on top of which templating is built on.
We've had Server-Side Includes and XSLT since the 90s, yet HTML templating should depend on JS? That's just silly.
Besides, there's a strong argument to be made for minimizing logic in templates or avoiding it altogether. Mustache and Handlebars have shown that this can work simply and elegantly. Whenever I see JS inside HTML attributes, I curse whoever came up with the idea. It's awful for legibility, maintainability, and plain sanity.
HTML can be a lot more capable without having to depend on JS. I think the discussion to drive this implementation forward would be well served by first principles thinking, instead of being inspired by modern web frameworks and JavaScript features.
I would be very interested in an API similar to the plates[1] library, but with support for event bindings (instead of being just a one-off rendering of plain HTML). My first thought is that it might not be very maintainable, and at best might only be useful for small templates or templates that are heavy on microdata[2].
But there's just something about this type of binding that makes me want to give it a serious chance, at least once, before completely giving up on it.
Yeah, Lit's tagged template literals and render() method are basically a shorthand for making a <template> element, marking the spots where expressions go, cloning the template, then filling in those sports.
You should use document.importNode() to clone templates.
Template contents are in a separate document from the main document, which is what makes them inert. importNode() adopts the nodes into the document so they have the correct prototype immediately (which includes custom elements). Otherwise the adopt steps are run when the elements are first attached to the document, which adds another tree walk to the insert/append operation that costs some time.
So:
document.importNode(elem.content, true);
Then you'll have a DocumentFragment you can pull nodes out of. Or just append the whole fragment.
<script> parses its contents as text, whereas <template> parses as DOM. This means you don't have to escape `<`, just `</script>`.
Myself and some browser engineers been working on proposals to allow for inline modules, including JSON, that are importable into other modules via regular import statements.
This is why I recommend the "-json" type - so it doesn't collide with a future native "json" type.
My understanding is that in implementations any unknown type creates a "data block", which is just unprocessed text.'
I wouldn't use application/json just in case browsers start supporting that and it has different semantics than whatever custom thing you might do, causing a webcompat issue when the native feature rolls out.
Although with JSON, it's pretty unlikely that there would be any differing semantics. JSON modules in JS are just JSON blocks with no special additions and no named exports. That's what inline versions would be as well.
But wouldn't a subtype like `mytype` in my example (`application/mytype+json`) still be be a valid mime-type and still avoid your concerns? I've used these before.
Yes, there are some people who say to build web components without shadow DOM, but I'm convinced they're only building leaf nodes so they don't need composition with slots. As soon as they try to build any kind of container element they hit big problems.