Web Components & the Shadow DOM

Intermediate · 24 min

Building framework-free, reusable UI with Custom Elements, Shadow DOM encapsulation, and HTML templates.

Before thisDOM Manipulation & Events

Web Dev Simplified · 24 min

Web Components & the Shadow DOM

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Custom Elements let you define a new HTML tag backed by a JavaScript class, with lifecycle hooks like connectedCallback that run when the element is actually inserted into the page.
  • Shadow DOM attaches a separate, hidden DOM tree to an element — CSS written inside it can't leak out, and page CSS can't reach in, which solves the styling-collision problem frameworks usually solve with build-time tricks.
  • <template> defines inert markup that exists in memory without being rendered until you clone it, which is the standard way to stamp out a custom element's internal structure repeatedly without re-parsing HTML strings.
  • <slot> is how a custom element accepts light-DOM children from its caller and decides where, inside its own shadow tree, those children actually render.
  • Web Components are a browser-native alternative to a framework's component model — no build step or runtime library required — which is exactly why they're a common choice for widgets meant to be dropped into any site, regardless of what framework that site runs.

The problem frameworks solve, minus the framework

Every major frontend framework gives you some version of the same thing: a reusable component with its own markup, styles, and behavior, that you can drop into a page as a custom tag. The catch is that a React component only works in a React app, and a Vue component needs Vue’s runtime to render at all. If you’re building a widget meant to be embedded on arbitrary third-party sites — an analytics badge, an embeddable chat button, a design-system primitive meant to outlive whatever framework your company is using this year — a framework dependency is a liability, not a convenience.

Web Components are the browser’s native answer: three APIs, built into every modern browser, with no library and no build step, that together let you define a real custom HTML tag with its own encapsulated behavior and style.

Custom Elements: a class, registered as a tag

The core piece is customElements.define('my-widget', MyWidgetClass), where MyWidgetClass extends HTMLElement. From that point on, <my-widget></my-widget> is a real, valid tag anywhere in your HTML, and the browser instantiates MyWidgetClass for every one it finds.

The class gets lifecycle hooks that matter because of a subtlety easy to miss: an element’s constructor can run before it’s actually placed in the document (for instance, if it’s created with document.createElement and held in memory). connectedCallback() is the hook that fires when the element is genuinely inserted into the live DOM — it’s where you should do setup that depends on the element actually being on the page, like fetching data or reading an attribute a caller set in markup. There’s a matching disconnectedCallback() for cleanup when the element is removed, and attributeChangedCallback() for reacting when an observed attribute changes.

Shadow DOM: a DOM tree the rest of the page can’t touch

Define a custom element and give it innerHTML directly, and you’ve gained a convenient tag — but its internal markup still lives in the same DOM tree as everything else, which means the page’s global stylesheet can still reach in and restyle it, and a generic div selector elsewhere can collide with one inside your component.

this.attachShadow({ mode: 'open' }), called inside the element’s constructor, solves this by giving the element its own separate DOM subtree — a shadow root — that’s rendered as part of the page but treated as a styling and (mostly) a structural boundary. CSS written inside a <style> tag within that shadow root only applies to nodes inside it; it cannot leak out and restyle the rest of the page. Just as importantly, the page’s own CSS can’t reach in and override styles inside the shadow tree either — a generic button { color: red } on the page will not touch a button living inside a component’s shadow DOM. This is the actual problem that CSS-in-JS and scoped-CSS build tools exist to solve in frameworks; Shadow DOM gives you the same guarantee natively, enforced by the browser rather than by a build step.

Templates: markup that doesn’t render until you ask it to

A <template> element is genuinely strange compared to normal HTML, and that’s the point: its contents are parsed by the browser into valid DOM nodes, but those nodes are never rendered on the page and any embedded <img> or <script> inside never runs — until you explicitly clone the template’s content with template.content.cloneNode(true). This is the standard way to define a custom element’s internal structure once, in markup rather than as a string of innerHTML you build up by hand, and stamp it out repeatedly — once per instance of your element — without re-parsing an HTML string on every single instantiation.

Slots: letting the caller put content inside your component

A component that only ever renders fixed content isn’t very reusable. <slot>, placed inside a shadow tree, is how a custom element accepts markup from whoever is using it and decides where that markup actually appears. If someone writes:

<my-card>
  <span>Some caller-provided content</span>
</my-card>

and my-card’s shadow tree contains a <slot></slot> somewhere inside its own layout, that <span> — which structurally still lives in the page’s regular “light DOM,” not inside the shadow tree — gets projected into that slot’s position visually. Named slots (<slot name="footer">, matched by slot="footer" on the child) let a single component expose several distinct insertion points — a header, a body, a footer — each filled independently by whoever uses the tag. This is what makes a Web Component genuinely composable rather than just a fixed, opaque box: the caller supplies content, the component supplies layout and behavior, and the two combine without either one knowing the other’s internals.

Check yourself

  1. 01What's the difference between a Custom Element's constructor and its connectedCallback?

    The constructor runs once, when the element is created, often before it's attached anywhere — connectedCallback runs every time the element is actually inserted into the document, which is the right place to do work that depends on the element being live on the page.

  2. 02Why can CSS written inside a Shadow DOM tree not accidentally style the rest of the page, or get overridden by it?

    The shadow tree is a separate DOM subtree with its own style scope, which the browser treats as a boundary — selectors inside it only match elements inside it, and the page's own stylesheets don't cross that boundary either, by design.

  3. 03What problem does <template> solve that just writing innerHTML = '...' doesn't?

    A <template>'s contents are parsed once but never rendered or executed until you explicitly clone them — so you get valid, reusable DOM nodes to stamp out repeatedly without re-parsing an HTML string or accidentally running embedded scripts or images on definition.

  4. 04If a custom element's shadow tree has a <slot> with no name attribute, where does an unmarked child placed inside that custom element in the page's markup end up?

    It renders wherever that default, unnamed slot appears inside the shadow tree — the light-DOM child is projected into that position, even though it structurally still lives outside the shadow tree.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark