Web Components: Shadow DOM, Slots, and Lifecycle
Most teams meet web components as consumers first: a date picker from a vendor, a design-system button that must work in both a React app and a plain PHP admin. The appeal is portability â a custom element is a real tag with a real lifecycle, usable from any framework or none. The friction comes from the parts the platform does not decide for you: where styles stop, how light-DOM children get projected inside a shadow root, and which accessibility work remains your job even after the encapsulation boundary is drawn.
This lesson assembles the three underlying specs â custom elements, shadow DOM, and HTML templates â into one working component, then covers the styling and integration decisions that separate a demo from something you would ship.
Three Specs, One Component Model
Web components are not a single API. Custom elements give you tag registration and a lifecycle. Shadow DOM attaches a private subtree with its own scope for styles and ids. HTML templates provide inert markup you clone instead of building strings. A component may use only custom elements â plenty of useful tags never attach a shadow root â but the full encapsulation story needs all three.
| Spec | Responsibility | You provide |
|---|---|---|
| Custom Elements | Tag registration, lifecycle callbacks | A class extending the built-in element base |
| Shadow DOM | Style and DOM encapsulation | attachShadow, inner structure, adopted styles |
| HTML Templates | Reusable inert markup | A template element and a clone step |
The Lifecycle, and Where State Belongs
Registration happens once per tag name, and the constructor runs for every instance â including ones parsed from markup before your script loads. That last detail is the classic bug: constructors must not read attributes or children, because the element may not be upgraded yet. Do that work in connectedCallback instead, and use attributeChangedCallback with a declared observation list for anything the outside world can change:
class RatingStars extends HTMLElement {
static get observedAttributes() { return ['value', 'max', 'readonly']; }
constructor() {
super();
this.attachShadow({ mode: 'open' });
this._value = 0;
}
connectedCallback() {
this.render();
this.shadowRoot.addEventListener('click', (event) => {
if (this.hasAttribute('readonly')) return;
const button = event.target.closest('button');
if (!button) return;
this._value = Number(button.dataset.rating);
this.setAttribute('value', String(this._value));
this.dispatchEvent(new CustomEvent('rating-change', {
detail: { value: this._value },
bubbles: true
}));
});
}
attributeChangedCallback() {
this._value = Number(this.getAttribute('value') || 0);
this.render();
}
disconnectedCallback() {
this.shadowRoot.removeEventListener('click', this);
}
render() {
const max = Number(this.getAttribute('max') || 5);
const stars = Array.from({ length: max }, (_, i) => {
const n = i + 1;
const on = n <= this._value ? 'on' : 'off';
return '<button type="button" data-rating="' + n + '" class="' + on + '" aria-label="' + n + ' stars">★</button>';
}).join('');
this.shadowRoot.innerHTML =
'<style>:host{display:inline-flex} button{background:none;border:0;font-size:1.5rem;cursor:pointer} .on{color:#f59e0b} .off{color:#cbd5e1} button:focus-visible{outline:2px solid #2563eb}</style>' +
'<div role="group" aria-label="Rating">' + stars + '</div>';
}
}
customElements.define('rating-stars', RatingStars);
The constructor here only attaches the shadow root; all attribute reading and event wiring happens after connection. The CustomEvent payload carries the new value and bubbles, which is how a web component integrates with ordinary DOM event delegation outside its boundary.
Slots: How Light DOM Gets Inside
A slot is a named projection point. Children written between the element's tags flow into the default slot; anything with a matching slot attribute fills the named one. Slotted children stay in the light DOM â they keep their global classes and event listeners â but render where the shadow markup places them. Assign them to slots with the slot attribute rather than moving nodes, which would break the original document structure.
This split is what makes composition possible: the component owns structure and internal styling; the page owns the content and the outer context. Unnamed slotted content still participates in the page's cascade, so a global reset can restyle your component's public face â sometimes a feature, sometimes an unpleasant surprise.
Styling Across the Boundary
Inside a shadow root, document-level styles stop applying. That isolation is the point, and also the tax: a global theme does not reach in uninvited. Three mechanisms bridge the gap in increasing order of control. Inheritable properties such as color, font, and line-height cross the boundary automatically â leaning on them covers half of theming needs. The :part pseudo-element exposes named internal pieces for external CSS. And custom properties, which also cross boundaries, let a component declare themeable slots:
/* From the page, styling internals exposed with part="star" */
rating-stars::part(star) {
transition: transform 120ms ease;
}
/* Inside the component stylesheet */
:host {
--rating-on: #f59e0b;
--rating-off: #cbd5e1;
display: inline-flex;
}
button.on { color: var(--rating-on); }
button.off { color: var(--rating-off); }
Constructable stylesheets take this further: one CSSStyleSheet object can be adopted by many shadow roots at once, so a design system ships styles without duplication and updates propagate when the shared sheet changes.
Templates Versus Building HTML Strings
The RatingStars example assigns innerHTML directly, which is fine for static internal chrome. When the internal markup is large or repeated, a template element keeps it inert in the document â parsed once, never rendered, free of per-instance parse cost â and cloneNode of its content supplies each instance. Templates also keep markup readable in the source rather than buried in string concatenation, and they avoid the escaping mistakes that concatenated HTML invites.
A typical setup places the template next to the component script, then clones it in the constructor or connectedCallback and fills in dynamic parts by reference rather than by re-parsing:
<template id="user-chip-tpl">
<style>
:host { display: inline-flex; align-items: center; gap: 0.5rem; }
img { width: 2rem; height: 2rem; border-radius: 9999px; }
.status { width: 0.5rem; height: 0.5rem; border-radius: 9999px; }
.status.online { background: #22c55e; }
.status.away { background: #f59e0b; }
</style>
<img alt="" src="" part="avatar">
<span part="name"><slot>Unknown user</slot></span>
<span class="status" part="status"></span>
</template>
<script>
class UserChip extends HTMLElement {
connectedCallback() {
const template = document.getElementById('user-chip-tpl');
const root = this.attachShadow({ mode: 'open' });
root.appendChild(template.content.cloneNode(true));
root.querySelector('img').src = this.getAttribute('avatar') || '';
root.querySelector('.status').classList.add(this.getAttribute('status') || 'online');
}
}
customElements.define('user-chip', UserChip);
</script>
Note the fallback text inside the slot element: if the page provides no children, screen readers and sighted users both get the default label. Note also that the img carries an empty alt â the accessible name comes from the slotted content, so a second announcement would be noise.
Templates scale better than string building for another reason: tooling. A build step can extract templates, lint the markup, and keep CSS next to the structure it styles, while concatenated strings are opaque to every analyzer you might run.
Where Web Components Fit Next to Frameworks
Custom elements interoperate through attributes and events. React registers attribute mapping for custom elements in modern versions; older setups need a small wrapper to forward property assignment and custom events. The stable contract stays the same one any consumer needs: properties for complex data, attributes for serializable configuration, DOM CustomEvents for notifications, and imperative methods for actions with no attribute equivalent. Design the API surface first in those terms, and the component works identically from Vue, Svelte, Angular, or a script tag.
Two integration details cause most of the remaining friction. First, event naming: custom events do not receive the automatic camel-case mapping that framework listeners expect, so dispatch names that are lowercase and hyphenated, exactly like native DOM events. Second, initial render timing: frameworks may instantiate a component and assign properties in separate ticks, so guard attribute reads with sensible defaults instead of assuming every property is present at connectedCallback time.
Accessibility Is Not Encapsulated
Shadow DOM hides structure from the document stylesheet, not from assistive technology â the accessibility tree is flattened across the boundary. That means roles, names, and keyboard behavior must be correct inside your shadow markup: label the group, wire keyboard interaction if you replace a native control, and never ship a div dressed as a button. The moment you replace a native element, you inherit every obligation that element carried for free.
Common Mistakes
Reading attributes or querying children in the constructor
Fix: Defer to connectedCallback â elements may not be upgraded when the constructor runs.
Expecting global CSS to style shadow internals
Fix: Rely on inherited properties, custom properties, and ::part for deliberate external styling.
Moving slotted nodes into the shadow tree
Fix: Leave children in the light DOM and project them through slots with the slot attribute.
Rebuilding the entire shadow root on every attribute change
Fix: Update only the changed nodes, or the component will lose focus and internal state constantly.
Replacing native controls without reimplementing keyboard and ARIA behavior
Fix: Prefer real buttons and inputs inside the shadow; add roles only when there is no native equivalent.
Best Practices
- Expose state through attributes, rich data through properties, and notifications through CustomEvents.
- Adopt a shared constructable stylesheet when many components must stay visually in sync.
- Use mode open shadow roots unless you have a concrete reason for closed â debugging closed roots is miserable.
- Test the component in at least two hosts: a framework app and a plain HTML page.
Key Takeaways
- Web components combine three specs: custom elements for lifecycle, shadow DOM for encapsulation, templates for reusable markup.
- Constructors must stay empty of DOM work; connectedCallback and attributeChangedCallback are the real setup points.
- Slots project light-DOM children into shadow markup without moving them â content stays owned by the page.
- Styles cross boundaries through inheritance and custom properties; ::part exposes internals on purpose.
- The portable API contract is attributes, properties, methods, and DOM events.
- Encapsulation hides CSS, not the accessibility tree â roles, names, and keyboard support remain your responsibility.