Chapter 12. Web Components
Introduction
Web components are a way to build new HTML elements with their own behavior. This behavior is encapsulated in a custom element.
Creating a Component
You can create a web component by defining a class that extends HTMLElement
, as shown in Example 12-1.
Example 12-1. A barebones web component
class
MyComponent
extends
HTMLElement
{
connectedCallback
()
{
this
.
textContent
=
'Hello from MyComponent'
;
}
}
When you add the custom element to the DOM, the browser calls the connectedCallback
method. This is typically where most of your component’s logic resides. This is one of the lifecycle callbacks. Some other lifecycle callbacks include:
disconnectedCallback
-
Called when you remove the custom element from the DOM. This is a good place to do cleanup, such as removing event listeners.
attributeChangedCallback
-
Called when you change one of the element’s watched attributes.
Registering a Custom Element
Once you’ve created your custom element class, you must register it with the browser before using it in an HTML document.
You can register your custom element by calling define
on the global customElements
object, as shown in Example 12-2.
Example 12-2. Registering a custom element with the browser
customElements
.
define
(
'my-component'
,
MyComponent
);
Note
If you try to define a custom element that has already been
defined, the browser throws an error. If this is a possibility for
you,
you can call customElements.get('my-component')
in order ...
Get Web API Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.