What Are Web Components?
Web Components are a set of modern web platform APIs that allow you to create reusable, encapsulated, custom HTML elements. They work natively in all major browsers without needing a JavaScript framework like React or Vue.
🛠️ Core Technologies of Web Components
Component | Description |
---|---|
Custom Elements | Define your own HTML tags using JavaScript |
Shadow DOM | Encapsulates styles and markup to avoid conflicts |
HTML Templates | Define HTML chunks that aren’t rendered until used |
✅ Benefits of Web Components
♻️ Reusable across projects and frameworks
🔒 Encapsulated styles and logic (no CSS leaks)
🚀 Lightweight and framework-agnostic
🧩 Easy to compose like native HTML elements
✍️ Example: Creating a Web Component
<!-- index.html -->
<hello-world></hello-world>
<script>
class HelloWorld extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: ‘open’ });
shadow.innerHTML = `<h1>Hello, Web Components!</h1>`;
}
}
customElements.define(‘hello-world’, HelloWorld);
</script>
✅ This defines a <hello-world>
custom HTML tag that shows a heading.
🎨 With Shadow DOM and Styles
class StyledBox extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
div { background: coral; padding: 10px; border-radius: 8px; }
</style>
<div><slot></slot></div>
`;
}
}
customElements.define('styled-box', StyledBox);
Usage:
<styled-box>Hello in a styled box!</styled-box>
🔗 Use Cases
Design systems (custom buttons, modals, etc.)
Micro frontends
Embeddable widgets (e.g., support chats, rating stars)
Reusable UI libraries (used in Salesforce, GitHub, etc.)
🧪 Browser Support
Browser | Support |
---|---|
Chrome | ✅ Full |
Firefox | ✅ Full |
Safari | ✅ Full |
Edge | ✅ Full |
IE11 | ❌ Not supported |
✅ No polyfill needed for modern browsers.
🧰 Tools & Libraries
Tool | Use Case |
---|---|
Lit | Simplified API for building web components |
Stencil.js | Compiler to generate standards-based components |
SkateJS | Lightweight wrapper for building UI components |
Vaadin | Enterprise-grade web component UI set |
🤔 Web Components vs React/Vue/Angular
Feature | Web Components | React/Vue/Angular |
---|---|---|
Framework-free | ✅ Yes | ❌ No |
Built-in HTML | ✅ Native | ❌ Requires compiler |
Style isolation | ✅ Shadow DOM | ⚠️ Scoped CSS |
Ecosystem | ⚠️ Smaller | ✅ Large |