chapter seven

7 Web Components

 

This chapter covers

  • The component design pattern
  • Breaking a user interface into reusable units
  • Building Vanilla Web Components
  • A walkthrough of the Custom Elements API and Shadow DOM
  • How to use CSS to style components

In the previous chapter, we covered how to use the DOM API to interact with a vanilla web user interface. In this chapter, we will begin with one of the most significant additions to the DOM API for creating maintainable, reusable applications: web components.

7.1 The component design pattern

The component design pattern breaks a user interface into small reusable parts that encapsulate structure, behavior, and style. They are everywhere in the app development world: in mobile native apps, desktop apps, and UI libraries. On a Vanilla web project, rather than sprinkling pieces of markup and script throughout a page, you define a component once and then reuse it wherever you need it.

Web Components are custom HTML elements that behave like built-in tags. They solve long-standing problems around code reuse by providing a built-in way to package markup, behavior, and styling together.

7.2 Use cases

7.3 Advantages

7.4 Challenges

7.5 Vanilla web components

7.5.1 Architecture

7.5.2 The puzzle

7.5.3 Abilities

7.6 Custom Elements API

7.6.1 Creation

7.6.2 Rendering content

7.6.3 Registration

7.6.4 Simplifying the syntax

7.6.5 The Custom Element Registry

7.7 Our first component

7.8 Shadow DOM

7.8.1 Creation

7.8.2 Styles with the page DOM

7.8.3 Styles with Shadow DOM

7.8.4 Styling web components

7.9 Element parameterization

7.9.1 data-* vs standard attributes

7.9.2 Boolean attributes