Web Components
Web Components are a bit
special because they let users define new components that extend the existing ones like
<dialog>.
As such they have an html part for declaration, a JavaScript part for behavior and a css part.
Their functionality can even be encapsulated away from the rest of your code.
The three parts of web components are:
- Custom Elements
- A set of JavaScript APIs that allow you to define custom elements and their behavior
- Shadow DOM
- A set of APIs for attaching an encapsulated "shadow" DOM tree to an element. Before declarative shadow dom this was only possible with JavaScript.
- HTML templates
- The
<template>and<slot>elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element's structure.
They have also been evolving over time and require less and less JavaScript.
A code-example of all three elements together (adapted from Web Components Guide):
// Create a new stylesheet that can be shared by all `my-element`
const styles = new CSSStyleSheet()
styles.replaceSync(`
:host {
font-size: var(--font-size-3);
font-style: italic;
}
`)
// Define the MyElement
class MyElement extends HTMLElement {
static define(tag = "my-element") {
customElements.define(tag, this)
}
// Give this element its own encapsulated DOM
shadowRoot = this.attachShadow({ mode: "open" })
connectedCallback() {
console.log("attached to the DOM");
// Add the shared styles
this.shadowRoot.adoptedStyleSheets = [styles]
}
}
// Register the element with the Custom Element Registry
MyElement.define();
Autonomous custom elements
Autonomous custom elements are HTML elements with a hyphenated tag name (like <example-element>)
that have behaviors you define.
Shadow DOM
Shadow DOM allows you to attach encapsulated "shadow" DOM trees to elements. A shadow DOM tree is a separate component, isolated from the scripts and styles in other parts of the document.
Declarative Shadow DOM
The shadowrootmode attribute on <template> creates a shadow root without the use of
JavaScript.
It is a declarative alternative to the attachShadow() method.
<template>
The <template> HTML element holds HTML fragments which you can clone and insert into
the document using JavaScript.
<slot>
The <slot> HTML element is a placeholder inside a web component where consumers of
the component can insert their own markup.