Web Components
Web Components is a suite of technologies allowing you to create reusable custom elements
3 main technologies:
- Custom elements set of APIs that allow you to define custom elements and their behavior
- Shadow DOM set of APIs for attaching an encapsulated shadow DOM tree to an element, rendered separately from the main document DOM, to keep an element's features private.
- HTML templates write markup templates using
template
andslot
elements that are not rendered in the rendered page.
Basic approach:
- Create a
class
or function in which you specify web component functionality - must use
super()
command at the top -
must contain a
constructor()
function that defines structure of Shadow DOM usingappendChild()
methods -
Use
CustomElementRegistry.define()
to link the componentclass
and the custom element - Attach a Shadow DOM to custom element using
Element.attachShadow()
and add children, event listeners, using regular DOM methods:const shadow = this.attachShadow({mode: 'open'})
- Define an HTML template using
template
andslot
- Use custom element at will on page.
2 types of custom elements:
- Autonomous custom elements are standalone and don't inherit from standard HTML elements, e.g.
<popup-info>
ordocument.createElement('popup-info')
. They almost always extendHTMLElement
- Customized built-in elements inherit from basic HTML elements, e.g.
<p is="word-count">
ordocument.createElement("p",{ is: "word-count"})
Lifecycle callbacks
adoptedCallback
invoked each time the custom element is moved to a new document
attributeChangedCallback
invoked when one of the custom element's attributed is added, removed, or changed
connectedCallback
invoked every time the custom element is appended into a document-connected element
disconnectedCallback
invoked each time the custom element is disconnected from the document's DOM