Web Components in HTML
You have met template, which keeps a blueprint, and slot, which leaves openings for content. Web components put these together with two more pieces, custom elements and shadow DOM, so you can invent your own HTML tags: <rating-stars>, <site-header>, <user-card>. They are plain browser features, with no library required, and they work in every modern browser.
What You Will Learnโ
- The four building blocks of a web component
- How to define a custom element, and the rules for its name
- Lifecycle callbacks, attributes, and properties
- How shadow DOM keeps styles and markup private, and what can still get through
- How components talk to the page with events
- How to load components and enhance pages progressively
- Accessibility and security points, and when to choose something else
The Big Ideaโ
A web component is a reusable tag that brings its own markup, its own styles, and its own behaviour, and works anywhere HTML works. The page author writes one line of HTML. The component takes care of the rest.
- Which Part?
- The Code
Match each job to the part of the web components toolkit that does it.
<!-- The page author writes plain HTML, with fallback text inside -->
<rating-stars value="3" max="5" label="Recipe rating">
Rating: 3 out of 5
</rating-stars>
<script type="module" src="/js/rating-stars.js"></script>
const template = document.createElement("template");
template.innerHTML = `
<style>
:host { display: inline-block; }
button { background: none; border: none; cursor: pointer;
font-size: 1.2rem; color: var(--star-color, goldenrod); }
</style>
<div class="stars" role="group"></div>`;
class RatingStars extends HTMLElement {
static get observedAttributes() { return ["value", "max"]; }
constructor() {
super();
this.attachShadow({ mode: "open" }).append(template.content.cloneNode(true));
}
connectedCallback() { this.render(); }
attributeChangedCallback() { this.render(); }
get value() { return Number(this.getAttribute("value")) || 0; }
set value(v) { this.setAttribute("value", String(v)); }
render() {
const box = this.shadowRoot.querySelector(".stars");
const max = Number(this.getAttribute("max")) || 5;
box.setAttribute("aria-label", this.getAttribute("label") || "Rating");
box.replaceChildren();
for (let i = 1; i <= max; i += 1) {
const star = document.createElement("button");
star.type = "button";
star.setAttribute("part", "star");
star.setAttribute("aria-label", i + " of " + max + " stars");
star.textContent = i <= this.value ? "โ
" : "โ";
star.addEventListener("click", () => {
// Dispatch first: setting value re-renders and removes this button
star.dispatchEvent(new CustomEvent("rating-change", {
detail: { value: i }, bubbles: true, composed: true
}));
this.value = i;
});
box.append(star);
}
}
}
customElements.define("rating-stars", RatingStars);
/* The page can change a colour through a custom property... */
rating-stars { --star-color: crimson; }
/* ...and restyle the parts the component chose to expose */
rating-stars::part(star) { font-size: 1.8rem; }
/* Style the not-yet-defined state */
rating-stars:not(:defined) { display: inline-block; }
The Four Building Blocksโ
| Block | What it gives you | Where you met it |
|---|---|---|
| Custom elements | Your own tag name, and code that runs when it is used | This lesson |
| Shadow DOM | Private markup and styles inside the element | This lesson |
| Templates and slots | Reusable markup, and openings for the page author's content | template, slot |
| ES modules | A clean way to load the component's code | Modern HTML Features |
You can use any of these on its own. A component usually uses all four.
Step 1: Custom Elementsโ
Namingโ
A custom element name must:
- contain a hyphen, such as
rating-stars, so it can never clash with a future built-in tag, - be lowercase, and start with a letter,
- not be one of the few reserved names that contain a hyphen already, such as
font-face.
Always write a closing tag. Custom elements cannot be self-closing, so <rating-stars /> does not work the way you expect.
Definingโ
A custom element is a JavaScript class that extends HTMLElement, registered with customElements.define. The first thing the constructor does is call super().
class RatingStars extends HTMLElement { /* ... */ }
customElements.define("rating-stars", RatingStars);
Until define runs, the browser treats the tag as an unknown element. When it runs, every matching element already on the page is upgraded. Open the Custom Element Lab and watch this: the element starts as plain text, and turns into stars when you press the button.
Lifecycle callbacksโ
| Callback | When it runs |
|---|---|
constructor() | The element is created. Keep it light: set up the shadow root, and nothing else |
connectedCallback() | The element is added to the page. A good place to render |
disconnectedCallback() | The element is removed. Clean up timers and listeners here |
attributeChangedCallback(name, old, new) | A watched attribute changes |
adoptedCallback() | The element is moved to another document (rare) |
In the constructor, do not read attributes or children, and do not add attributes or children to the element itself. At that moment, they may not exist yet. Do that work in connectedCallback.
Attributes and propertiesโ
- Attributes are what the page author writes in HTML. List the ones you watch in
static get observedAttributes(), andattributeChangedCallbackwill run when they change. - Properties are what JavaScript uses, such as
element.value. A neat habit is to reflect a property to an attribute, as thevaluegetter and setter do, so HTML and JavaScript stay in sync. - Attributes are always strings. Convert them yourself, and validate them, as the lab's
maxgetter does.
Useful extrasโ
:definedis a CSS pseudo-class that matches once an element is upgraded.:not(:defined)styles the waiting state.customElements.whenDefined("rating-stars")returns a promise that resolves once the tag is defined.
Step 2: Shadow DOMโ
attachShadow({ mode: "open" }) gives the element a shadow root, a private tree for its markup and styles.
const root = this.attachShadow({ mode: "open" });
- Styles inside do not leak out, and the page's rules do not reach in. A
buttonrule in your component only affects the component's buttons. openmeanselement.shadowRootreturns the root.closedhides it from casual access, but this is not security. See below.
What can still cross the boundaryโ
Encapsulation is not a wall. A few things are meant to cross, and they are how you make components flexible:
| Way in | How it works |
|---|---|
| Inherited properties | Things like color, font-family, and line-height flow into the shadow DOM from the host's parents |
| CSS custom properties | --star-color set on the page is readable inside, through var(--star-color, goldenrod) |
::part() | The component marks elements with part="star", and the page styles them with rating-stars::part(star) |
::slotted() | The component styles top-level slotted elements. See slot |
:host | The component styles its own host, such as :host { display: inline-block; } |
Custom elements are display: inline by default, so one of the first rules most components need is :host { display: block; } or inline-block.
In the lab, the colour list sets a custom property on the element, and the checkbox uses ::part(star) from the page's CSS. Both reach inside the shadow root, and nothing else does.
Step 3: Templates and Slots Insideโ
A tidy component keeps its markup in a template and clones it into the shadow root, as in the code above. Add slot elements where the page author's content should appear, so authors can write <user-card><h3 slot="name">Ada</h3></user-card>. The two earlier lessons cover the details.
Step 4: Talking to the Page With Eventsโ
A component should send information to the page the same way built-in elements do: with events.
// dispatched from an element inside the shadow root
button.dispatchEvent(new CustomEvent("rating-change", {
detail: { value: 4 },
bubbles: true,
composed: true
}));
detailcarries your data.bubbleslets the event travel up through the page, so a listener on a parent can catch it.composedlets it cross the shadow boundary. Without it, the event stays inside the shadow root.
The rule of thumb is data down, events up: the page sets attributes and properties to give the component data, and the component sends events to tell the page what happened.
Retargetingโ
When an event from inside a shadow root reaches the page, the browser retargets it: event.target shows the host element, not the button inside. The real source is available with event.composedPath()[0] (for open roots). The lab's log shows both.
Step 5: Loading and Progressive Enhancementโ
Load component code with a module script, which is deferred by default:
<script type="module" src="/js/rating-stars.js"></script>
Then design for the time before the component is ready, and for visitors where it never runs:
- Put useful content between the tags. "Rating: 3 out of 5" shows until the component takes over. After the upgrade, light DOM content with no slot is simply not drawn.
- Reserve space with CSS on
:not(:defined), so the page does not jump when the component appears. - Do not hide the content until JavaScript arrives, if the content matters.
Declarative shadow DOMโ
You can also ship a shadow root in the HTML itself, with <template shadowrootmode="open">, so a component can have its structure and styles before any script runs. This is useful for server-rendered pages. It works when the HTML parser reads the page, and support is newer, so check MDN.
Accessibilityโ
A custom element has no built-in meaning. To the browser it is a generic element, with no role and no keyboard behaviour. You supply those.
- Use real elements inside: a
buttonfor a button, aninputfor a field, a heading for a heading. They bring roles, focus, and keyboard support for free. The lab's stars are realbuttonelements. - Give things names. Take labels from attributes (such as
label), and set them withsetAttributeandtextContent, notinnerHTML. - Remember the boundary. IDs inside the shadow root and in the page are separate, so
label forandaria-labelledbydo not cross it. See slot. - Focus.
attachShadow({ mode: "open", delegatesFocus: true })helps when clicking the host should focus an inner control. - Form fields. A field hidden in a shadow root does not submit with the page's form. For a custom form control, look up "form-associated custom elements", or slot a real
input. - Test with the keyboard, a screen reader, and at 200% zoom.
Avoid customized built-in elements, written as <button is="fancy-button">. They extend a real element like a button, which would give free accessibility, but not every major browser supports them. Prefer an autonomous element that uses a real button inside.
When to Use Web Componentsโ
| Good fit | Weaker fit |
|---|---|
| Widgets and design-system pieces shared between teams, sites, or frameworks | A large app with lots of changing state and routing, where a framework helps |
| Small, self-contained features, such as a rating, a tabs widget, or a video player | A one-off piece of markup that appears once |
| Enhancing static or server-rendered pages | Anything that must work with no JavaScript at all |
| Embeddable widgets that must not clash with the host page's CSS | Simple repeated markup, where a template or plain HTML is enough |
Web components and frameworks also mix well. Most frameworks can use custom elements, and many can produce them.
Checking Your Setupโ
- In DevTools Elements, find
#shadow-root. Expand it to see the component's private markup. - In the Console, run
customElements.get("rating-stars")to confirm the tag is defined. - Check
document.querySelector("rating-stars").shadowRootfor an open root. - Click inside the component, and look at the event in a page-level listener. What is
event.target? - Remove JavaScript or the script, and look at the fallback.
- Test every control with the keyboard.
- Try right-to-left text, long labels, and 200% zoom.
- Check the Console for errors on page load, and for CSP messages.
Best Practicesโ
- Name tags with a hyphen, and a clear prefix for your project.
- Keep the constructor light, and render in
connectedCallback. - Use
observedAttributesand reflect properties to attributes. - Validate every attribute.
- Use real elements inside, for accessibility.
- Expose a small, documented surface: attributes, events, slots,
parts, and custom properties. - Send events with
composed: truewhen the page needs them. - Put useful content in the light DOM as a fallback.
- Clean up in
disconnectedCallback. - Document your component, so others can use it.
Quick Checklistโ
- The tag name has a hyphen and a closing tag
- The constructor only sets up the shadow root
- Attributes are validated, and watched through
observedAttributes - Inside the shadow DOM are real, accessible elements
- Events cross the boundary with
composed: true, where needed - The page's CSS can restyle through custom properties and
::part - Something sensible shows before the component loads
- No visitor data goes into
innerHTML - The component works with the keyboard and a screen reader
Security and Privacy Notesโ
- Shadow DOM is not a security boundary. Scripts on the page can reach into an open root, and
closedmode only makes casual access harder. Never keep secrets inside a component. - Attributes and slot content are untrusted input. If a
labelattribute holds markup and you put it intoinnerHTML, you have created cross-site scripting. UsetextContentandsetAttribute. See XSS Basics. - Use a fixed string or a
templatefor the component's markup. Never build it from visitor text. - Third-party components run with the full power of your page. Treat a component like any script: trust the source, use
https, pin versions, and considerintegrity. See Third-Party Content Security. - Your Content Security Policy still applies. Inline
styleelements inside a shadow root follow the same style rules as the page. Check how your policy treats them. See Content Security Policy. - Events carry data. Do not put sensitive information in
detail, because any listener on the page can read it.
Global Audience Notesโ
- Take every visible word from outside the component (attributes or slots), so each page can supply its own language. Avoid hard-coding English in the shadow DOM.
- Right-to-left languages: use logical properties such as
margin-inline-start, and test. Newer CSS also offers a:dir()selector for direction-specific rules. - Fonts and sizes inherit, so users' language and zoom settings carry through.
- Components make good shared widgets across regions, but each region's text, numbers, and dates need to be formatted with
Intl, not by hand. - Weak devices and networks: keep components small, load them with
type="module", and give a readable fallback.
Common Mistakes to Avoidโ
- Forgetting the hyphen in the tag name.
- Writing a self-closing tag.
- Reading attributes or adding children in the constructor.
- Forgetting
observedAttributes, so changes are ignored. - Using
innerHTMLwith attribute or visitor text. - Not setting
displayon:host, and wondering about layout. - Expecting page CSS to reach inside, instead of exposing
::partor custom properties. - Forgetting
composed: true, so the page never hears the event. - Building controls from
divs, with no roles or keyboard support. - Showing nothing until the script loads.
Practice Timeโ
- In the lab, read the line above the stars. What does the page show before the element is defined?
- Press Define. What happens to the text you saw?
- Click a star. What does the log say about
event.targetand the real source? - Change the number of stars, then the colour. Which attribute and which CSS property are you changing?
- Tick the
::partbox. What does the page's CSS reach? - Complete the Which Part? matcher.
- Write a
user-cardcomponent with a default slot and anameslot, and a fallback for each. - Bonus: add
disconnectedCallbackto a component that uses a timer, and make sure it stops.
Quick Recapโ
Click a question to check your answer.
1. What are the four building blocks of web components?
Custom elements, shadow DOM, templates and slots, and ES modules.
2. What are the rules for a custom element name?
It must contain a hyphen, be lowercase, start with a letter, and avoid a few reserved names. Always write a closing tag.
3. What should the constructor and connectedCallback each do?
The constructor stays light, setting up the shadow root. connectedCallback runs when the element joins the page, and is the place to render and read attributes.
4. What can cross the shadow boundary?
Inherited CSS properties, CSS custom properties, ::part styling, slotted content, and composed events.
5. Why use composed: true on an event?
Without it, a custom event stays inside the shadow root. With it, the event crosses the boundary, so the page can listen for it.
6. Is shadow DOM a security feature?
No. Scripts can reach into an open root, and closed mode is not protection. Treat attributes and slotted content as untrusted, and never put secrets in a component.
Key Takeawaysโ
- Web components are your own HTML tags: custom elements, shadow DOM, templates and slots, and modules.
- Name with a hyphen, define with
customElements.define, and render inconnectedCallback. - Shadow DOM keeps markup and styles private. Custom properties,
::part, and slots are the controlled ways in. - Data down, events up, with
composed: trueevents. - Use real elements inside, for accessibility.
- Put useful content in the light DOM, for fallback and progressive enhancement.
- Treat attributes as untrusted, and never use shadow DOM for secrets.
You have now covered every building block of modern HTML in this section. One lesson remains: Lazy Loading, which looks at native lazy loading for images and frames as part of the modern toolbox.