Web Components are a set of technologies that allow for custom, native HTML elements
A Shadow DOM is an encapsulated DOM tree
A Shadow DOM is created programmatically
const node = document.querySelector('.myNode');
const child = document.createElement('div');
node.attachShadow({ mode: 'open' });
node.shadowRoot.appendChild(child);
HTML Templates define the structure of a DOM node and it's children
A basic template
<template name="confirm-dialog">
<div><slot name="title-slot">Confirm</slot></div>
<div>
<slot></slot>
</div>
<div>
<button>Ok</button>
</div>
</template>
Custom Elements define named HTML elements and behaviors
Autonomous Custom Elements are standalone elements
<my-custom-element someAttribute="value">
Content!
</my-custom-element>
Custom build-in elements extends the functionality of a built-in element
<p is="my-custom-element"></p>
class MyCustomElement extends HtmlElement {
constructor() {
// initialize the structure
}
}
All Custom Elements have a standard lifecycle
connectedCallback() is called when the element is connected to the DOM
Use it to programmatically alter and set-up the element
disconnectedCallback() is called when the element is removed from the DOM
Use it to destroy and deallocate
adoptedCallback() is called when the element is moved between documents
Use it to marvel at the wonders of the DOM
class MyCustomElement extends HtmlElement {
static get observedAttributes() {
return [ 'attributeName' ]
}
attributeChangedCallback(name, oldValue, newValue) {
// handle attributes
}
}
There are two types of Web Component frameworks