Web Components: Custom Elements

Hello!

Paul Shannon

  • Sr Engineer @ SitePen
  • Talkscript Podcast
  • Phoenix TypeScript
  • Committer: Dojo, Intern
  • devpaul

What are Web Components?

Web Components are a set of technologies that allow for custom, native HTML elements

  • Shadow DOM
  • HTML Templates
  • Custom 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

  • <template>
  • <slot>

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>
			

How do shadow DOM and templates work together?

Custom Elements define named HTML elements and behaviors

  • Autonomous custom element
  • Custom built-in element

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>
			

Creating a Custom Element


				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

Custom Attributes


				class MyCustomElement extends HtmlElement {
					static get observedAttributes() {
						return [ 'attributeName' ]
					}

					attributeChangedCallback(name, oldValue, newValue) {
						// handle attributes
					}
				}
			

Web Component Frameworks

There are two types of Web Component frameworks


  • Pure (Svelte, Stencil, Polymer)
  • Framework Wrapped (Angular, Dojo, Vue)

Web Components Benchmark

https://vogloblinsky.github.io/web-components-benchmark/

Questions?