What are Web Components?
📅
Definition
Web Components are not a library or a framework. They are a set of browser standards that allows you to create your own, encapsulated, and reusable HTML tags. Essentially, it's a native implementation of the component approach, built right into the web platform.
The key technologies included in the standard are:
- Custom Elements — allows you to define your own HTML tags (e.g.,
<user-card>or<fancy-button>). - Shadow DOM — provides true encapsulation for the component's styles and structure. Styles inside the component do not leak out, and external styles do not affect the component's internals.
- HTML Templates (
<template>and<slot>) — allow you to describe markup fragments that are not displayed when the page loads but can be used and cloned later in the component's code.
Want to see what it looks like?
Basic Example
<!-- 1. Declare the component -->
<hello-world></hello-world>
<script>
// 2. Create the class
class HelloWorld extends HTMLElement {
connectedCallback() {
this.innerHTML = `<p>Hello, world!</p>`;
}
}
// 3. Register it
customElements.define('hello-world', HelloWorld);
</script>
or even without JS:
<hello-world>
<template shadowrootmode="open">
<p>Hello, world!</p>
</template>
</hello-world>
</script>
The component is created. This is all valid and works in any modern browser, without any bundlers or other add-ons. You can open it yourself and see.
Browser Support
| Browser | Custom Elements | Shadow DOM | Templates |
|---|---|---|---|
| Chrome | ✅ Full | ✅ Full | ✅ Full |
| Firefox | ✅ Full | ✅ Full | ✅ Full |
| Safari | ✅ Full | ✅ Full | ✅ Full |
| Edge | ✅ Full | ✅ Full | ✅ Full |
| IE11 | ❌ No | ❌ No | ⚠️ Partial |
Polyfills
For older browsers, include:
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.8.0/webcomponents-bundle.js"></script>
Important: Polyfills add ~20 KB to the page weight. Use only if necessary.