What are Web Components?
Web Components are a set of browser APIs that allow you to create new custom, reusable, encapsulated HTML tags. They work in any framework (React, Vue, Svelte) or even with no framework at all.
They consist of three main technologies:
- Custom Elements
- Shadow DOM
- HTML Templates
1. Custom Elements
You can define a new tag by extending the
HTMLElement class and registering it with the browser.javascript
Usage:
<my-button></my-button>2. Shadow DOM (Encapsulation)
Shadow DOM allows you to attach a separate, hidden DOM tree to an element. This ensures that the styles inside your component don't "leak out" and affect the rest of the page, and external styles don't "leak in."
javascript
3. HTML Templates and Slots
The
<template> tag allows you to define HTML that is not rendered until you instantiate it. <slot> is used to create placeholders for dynamic content.html
4. Lifecycle Callbacks
connectedCallback: Called when the element is added to the DOM.disconnectedCallback: Called when removed from the DOM.attributeChangedCallback: Called when an attribute (likeidorsrc) changes.
5. Why use them?
- Interoperability: Build a UI library that works in any environment.
- Encapsulation: No more CSS naming collisions.
- Future-proof: Native browser support means no dependencies to update.
Summary Checklist
- Extend
HTMLElementto create a Custom Element. - Use
customElements.defineto register the tag. - Use
attachShadowfor style and DOM isolation. - Use
<slot>for content projection. - Native support in 100% of modern browsers.