Template, Slot & Web Components
20 min read
templateslotWeb ComponentsCustom ElementsShadow DOMShadow Parts
Web Components: Framework-Free Components
Web Components are a set of browser-native APIs that let you create reusable, encapsulated custom elements — no React or Vue required.
The Three Pillars
- Custom Elements: Define your own HTML tags like
<user-card> - Shadow DOM: Encapsulate styles so they do not leak in or out
- HTML Templates: Define markup that is not rendered until cloned
The <template> Element
Content inside <template> is parsed but NOT rendered. It exists as a DocumentFragment you can clone and insert.
Slots: Content Projection
<slot> elements define where consumer content should appear inside a shadow DOM. Named slots allow multiple insertion points.
Shadow DOM Encapsulation
- Styles inside shadow DOM do NOT affect the rest of the page
- External styles do NOT affect shadow DOM content
- JavaScript querySelector from outside cannot reach into shadow DOM
::part()CSS pseudo-element allows controlled external styling
Lifecycle Callbacks
| Callback | When |
|---|---|
| connectedCallback | Element added to DOM |
| disconnectedCallback | Element removed from DOM |
| attributeChangedCallback | An observed attribute changes |
| adoptedCallback | Element moved to new document |