Web Components Overview

Web components are HTML elements that are not built into the browser, but are created by developers. 

Web components are broad term for a couple of specifications that are built in modern browsers:

  • Custom HTML element – register your own HTML Tags.
  • Shadow DOM – manage a separate DOM node tree for your HTML elements (including scoped CSS styles)
  • Templates and Slots – Write HTML templates that you can add to your HTML elements
  • HTML Imports –  The process stopped, the industry moved in another direction using javascript modules and modern build  tools.

The advantages for using web components are:

  • Encapsulate logic + UI – easy to understand, easy to maintain and separation of concerns
  • Reusable across page – use it just like a normal HTML element and writing logic + UI only once
  • Reusable between projects – Re-use core UI elements across projects and we can publish as a package via npm

Web Components Lifecycle

  • constructor() – element created`- basic initialization
  • connectedCallback() – element attached to DOM – DOM initialization
  • disconnectedCallbcak() – element attached from DOM – cleanup
  • attributeChangedCallback() – observed attribute callback – update DATA + DOM

There are 2 ways of creating web components:

  • Extending an exiting html element
  • Extending a specific html element

When we create a web component we can use the following things:

  1. Use a constructor which we always have to call super first.
    • Making some initialization
    • Set up the shadow DOM
    • Initialize the template (html, css and slots) 
  2. Use the lifecycle hooks
    • The most important is the connectedCallback lifecycle hook. When connectedCallback run, the custom element have been added to the real DOM, which then we can:
      • Do DOM manipulations on the element itself  (not on the shadow DOM that is possible earlier), 
      • Get access to its attributes
  3. Register the custom element with the define method (uc-blabla)
  4. Add properties and methods to the class that we can call from other place