Web Components

A way of creating (“browser native”) separate components/elements with HTML, CSS and Javascript.

The Web components technology consists of three different sub-technologies:

  1. Custom elements
  2. Shadow DOM
  3. HTML templates with <template> and <slot>

1. Custom elements

User-definable HTML elements.

To define elements use CustomElementRegistry: customElements.define(name, constructor, options)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class CustomElement extends HTMLElement {
	constructor() {
		super();
		// Set up shadow DOM
		// Set up styles
	}

	// ...
}
customElements.define(
	'custom-element',   // name
	CustomElement,      // class
	{ extends: 'kbd' }  // options
);

You can specify that an in-build element should behave as a custom one using is: <kbd is="custom element">...</kbd>

Lifecycle calbacks

These are added ass methods in the element class.

2. The Shadow DOM

3. HTML templates

Related Articles