Chapter 7: Web components
Introduces web components as the chapter’s approach to building maintainable, reusable user interfaces and previews the topics ahead.
After this chapter you will be able to
- Reusable UI component pattern. Explain how the component design pattern organizes a UI into reusable parts instead of scattering markup and scripts across a page.
- Custom elements and interfaces. Describe how a web component fits alongside built-in HTML elements and how a parent page uses it.
- Encapsulation and framework portability. Justify why self-contained, standards-based components help maintain growing applications and move between projects or frameworks.
- Two component use cases. Distinguish generalizable components that extend HTML across projects from project-specific components that represent parts of one application.
- Custom element definition and use. Explain how the section defines and uses a basic custom element: extend HTMLElement, register the class with customElements.define(), then import its module and write its tag in HTML.
- Shadow DOM encapsulation. Explain how attaching a shadow DOM can keep a component’s internal elements and styles separate from the page, preventing styles from leaking in either direction.
- Cross-project component reuse. Explain why a well-designed web component can be shared across projects, teams, and frameworks without depending on a particular framework.
- Native platform integration. Describe how standard web components work with ordinary browser features and contrast their rendering overhead with framework components.
- Manual component plumbing. Explain why building a Web Component can require more code than using a framework: developers manually handle attributes, state, DOM updates, and events, and must add code to respond to property changes.
- Component use-case fit. Explain why the section favors Web Components for generalizable elements over project-specific reactive UI.
- Browser component building blocks. Describe the high-level role of Custom Elements, Shadow DOM, HTML templates, and Element Internals in a vanilla web component.
- Framework optional component model. Explain how browser APIs support the component pattern without a framework and what libraries such as Lit or Stencil add.
- Host and shadow structure. Describe the host element and optional shadow DOM tree in a web component, including what each contains or represents.
- Component public contract. Distinguish attributes, properties, methods, and events by how each lets the host page configure, use, or hear from a component.
- Component creation sequence. Trace what happens when the browser encounters a custom tag, from constructing the element through preparing its DOM and handling later changes.
- Custom element and interface. Explain that a custom element is a new HTML element defined and registered in the browser, and that its interface lets consumers set data and read data and changes.
- Page and shadow DOM boundary. Distinguish the consumer’s document or page DOM from the shadow DOM inside a custom element, and identify the host element as their boundary.
- Light DOM and slots. Describe light DOM as children supplied by the component’s consumer, and a slot as a placeholder inside shadow DOM that displays that content.
- Web Component capabilities. Describe, at a high level, capabilities Web Components add beyond plain HTML, such as creating a tag, encapsulating markup and CSS, and passing data through attributes or properties.
- Custom Elements API role. Explain how the Custom Elements API lets developers give HTML elements custom behavior and how custom elements relate to web components.
- Two custom element kinds. Distinguish autonomous custom elements from customised built-in custom elements, including why autonomous elements are more commonly used.
- Registration and initial callbacks. Describe how a custom element’s class is registered and what happens when the browser encounters and inserts its tag.
- Custom element initialization timing. Explain why an autonomous custom element extends HTMLElement and why its constructor should call super() and initialize state without reading HTML attributes or child nodes.
- Connected callback DOM access. Describe how connectedCallback() is used to access the element's attributes and nodes, set its content, and perform DOM work through this.
- Custom element rendering strategies. Describe the four rendering strategies named here and their basic tradeoffs: creating DOM nodes, setting innerHTML, cloning a template, or loading external HTML.
- Safe user content rendering. Explain why unsanitized user input must not be inserted through innerHTML and what to use for text-only content or user-supplied HTML.
- Custom element registration. Explain that customElements.define(name, constructor) makes a custom element available to the page by associating its tag name with the class or constructor that defines it, and describe what happens if the tag is used without registration.
- Element creation and connection. Describe using a registered custom element in HTML or JavaScript, including when its constructor and connectedCallback run and why constructor arguments are not recommended for parameterization.
- Simpler custom element syntax. Explain that a custom element can be defined with a literal class, or presented in a function-like style through a helper. Distinguish the example micro-library from actual web platform API syntax.
- Registry access and readiness. Explain where the CustomElementRegistry is available and distinguish checking whether a custom element is registered from waiting for its registration.
- Independent counter button instances. Explain how multiple <counter-button> elements can reuse one component while keeping separate buttons and counter values.
- Defined and pending elements. Distinguish what :defined and :not(:defined) match and explain their use while custom elements await registration.
- Shadow DOM encapsulation boundary. Explain how attaching a shadow root separates a component’s internal DOM from the page DOM and why that makes custom elements less vulnerable to page CSS and JavaScript.
- Shadow root and host roles. Explain how a component creates a shadow root and why internal content is rendered through the root rather than the host element.
- Open and closed shadow modes. Distinguish open and closed shadow modes by outside access to the shadow root, and explain what closed mode does not protect.
- Shared page DOM styles. Explain why styles can affect both the page and a custom element when the element does not use a shadow root, using the button and heading example.
- Shadow DOM style isolation. Explain how moving MyComponent’s innerHTML into an attached shadow DOM isolates its style declarations from global styles, and use the button and h1 example to describe the result.
- Shadow root style encapsulation. Justify the recommendation to put styles in a shadow root except for elementary elements, and describe the risk of relying on page styles.
- Shared adopted stylesheets. Explain how a constructible stylesheet is populated and adopted by a shadow root, and why sharing it differs from putting a separate <style> element in every instance.
- Attributes and properties. Distinguish HTML attributes from JavaScript properties as ways to pass values to a custom element. Explain which kinds of values each typically suits and why accepting values makes a component reusable.
- CSS-based visual customization. Explain why CSS is preferred over attributes for visual styling and describe what a consumer can customize through CSS custom properties.
- Component attribute design. Distinguish core component configuration from application-specific metadata when choosing attributes. Explain why standard attributes are preferred for settings such as variant or size, while data-* attributes suit values such as product IDs or indexes.
- Boolean attribute presence. Explain that a boolean attribute is true when present and false when absent, regardless of its written value. Describe why a custom element should use hasAttribute() rather than the string returned by getAttribute() to check it.
- Observed attribute registration. Explain how to declare which attributes a custom element observes and why an attribute must be on that list for change notifications to occur.
- Attribute change updates. Describe what attributeChangedCallback receives and how a component can use it to update its content when an observed attribute changes after initial rendering.
- Property changes and component updates. Explain why a web component that exposes a property-based API should update when that property changes, and describe how a setter can provide a place to trigger the update.
- Star rating value attribute. Explain how the example star-rating component represents a rating and what <star-rating value='3'></star-rating> displays.
- Custom element event communication. Explain how a custom element exposes an internal occurrence to consumers by dispatching a CustomEvent, and how consumers listen on the element. Describe what detail, bubbles, and composed control.
- Page-defined theme properties. Explain that CSS custom properties cross the shadow DOM barrier, allowing a component to use theme values defined in the page DOM without explicitly mapping or defining them inside the component.
- Custom properties across shadow DOM. Explain how a component can use CSS custom properties set on its host by the page, even though ordinary page styles do not affect the shadow tree. Describe how the component uses var() and supplies defaults with :host that page-defined values can override.
- Exposed shadow DOM parts. Explain how a component names selected shadow DOM elements with the part attribute so consumers can style them from page CSS using ::part(), without accessing the entire shadow tree.
- Host selector state styling. Explain how :host(selector) lets a web component style itself according to a class or attribute on its host element, and distinguish it from unconditional :host.
What it builds on
- The DOM tree (chapter 6) · The idea of elements participating in the DOM tree.
- HTMLElement interface (chapter 6) · Familiarity with HTMLElement as a DOM interface.
- Creating elements (chapter 6) · Introduces creating DOM elements.
- Classes with public & private fields (chapter 5) · Introduces JavaScript classes.
- Modifying elements (chapter 6) · Introduces modifying DOM elements.
- ECMAScript Modules (chapter 5) · Modules and their import-time execution.
- Custom properties with dataset (chapter 6) · Introduces data-* attributes and dataset.
- Properties vs. attributes (chapter 6) · Introduces DOM attributes as distinct from properties.
Section by section
Introduction
Introduces web components as the chapter’s approach to building maintainable, reusable user interfaces and previews the topics ahead.
7.1 The component design pattern
This section explains how the component pattern packages reusable UI, what web components are, and why their encapsulation and interoperability matter.
- Reusable UI component pattern: Explain how the component design pattern organizes a UI into reusable parts instead of scattering markup and scripts across a page.
Why it matters: This is the organizing idea behind the web components built later in the chapter. - Custom elements and interfaces: Describe how a web component fits alongside built-in HTML elements and how a parent page uses it.
Why it matters: Thinking of a component as an element with an interface clarifies how a page can use it without managing its internals. - Combined browser standards: Distinguish the Web Components design pattern from a supposed single browser API.
Why it matters: This prevents you from looking for one all-encompassing API when the chapter introduces the browser capabilities involved. - Encapsulation and framework portability: Justify why self-contained, standards-based components help maintain growing applications and move between projects or frameworks.
Why it matters: These benefits explain why components are useful beyond simply making custom tags.
Key terms: component design pattern, structure, behavior, style, Web Components, custom HTML elements, DOM, attributes, properties, events
7.2 Use cases
This section distinguishes reusable and application-specific web component use cases, then shows how a custom element becomes usable in HTML.
- Two component use cases: Distinguish generalizable components that extend HTML across projects from project-specific components that represent parts of one application.
Why it matters: The distinction helps you decide whether a component is a reusable building block or belongs to a particular app. - Custom element definition and use: Explain how the section defines and uses a basic custom element: extend HTMLElement, register the class with customElements.define(), then import its module and write its tag in HTML.
Why it matters: This connects a JavaScript component definition to the HTML tag a page actually uses.
Key terms: generalizable components, project-specific components, web component, custom element, HTMLElement, customElements.define()
7.3 Advantages
This section explains how web components improve on ad hoc script-driven markup through encapsulation, reuse across projects and frameworks, and integration with browser features.
- Shadow DOM encapsulation: Explain how attaching a shadow DOM can keep a component’s internal elements and styles separate from the page, preventing styles from leaking in either direction.
Why it matters: Style isolation makes a component less likely to be disrupted by, or disrupt, the page using it. - Cross-project component reuse: Explain why a well-designed web component can be shared across projects, teams, and frameworks without depending on a particular framework.
Why it matters: A component can be shared without tying every team or project to the same framework. - Native platform integration: Describe how standard web components work with ordinary browser features and contrast their rendering overhead with framework components.
Why it matters: Components fit into familiar browser workflows rather than needing a separate framework model.
Key terms: encapsulation, shadow DOM, private subtree, global CSS, reusability, interoperability, custom element, framework dependencies, event flow, CSS selectors
7.4 Challenges
This section explains the extra implementation work, uneven API support, and use-case limits of Web Components.
- Manual component plumbing: Explain why building a Web Component can require more code than using a framework: developers manually handle attributes, state, DOM updates, and events, and must add code to respond to property changes.
Why it matters: It explains why a native component may still need substantial application code. - Uneven API support: Distinguish broad support for basic Web Component APIs from the potentially partial support of newer APIs such as form-associated custom elements.
Why it matters: It helps you avoid assuming that support for basic components covers every feature you might use. - Component use-case fit: Explain why the section favors Web Components for generalizable elements over project-specific reactive UI.
Why it matters: It gives you a practical reason to choose where components are worth using.
Key terms: Custom Elements API, attributes, state, DOM, events, reactivity, Baseline, form-associated custom elements, generalizable elements, reactive templating
7.5 Vanilla web components
Introduces the browser APIs that provide vanilla web components and explains how libraries build on them without being required.
- Browser component building blocks: Describe the high-level role of Custom Elements, Shadow DOM, HTML templates, and Element Internals in a vanilla web component.
Why it matters: These distinct browser capabilities are the foundation for the component techniques developed later. - Framework optional component model: Explain how browser APIs support the component pattern without a framework and what libraries such as Lit or Stencil add.
Why it matters: It distinguishes native web components from optional conveniences supplied by libraries.
Key terms: Custom Elements, CustomElementRegistry, Shadow DOM, HTML templates, ElementInternals, component pattern, framework, Lit, Stencil, templating syntax
7.5.1 Architecture
This section explains the parts of a web component, its public contract with the host page, and the basic sequence from creation to later lifecycle callbacks.
- Host and shadow structure: Describe the host element and optional shadow DOM tree in a web component, including what each contains or represents.
Why it matters: It separates the element a page uses from the optional tree that renders its contents. - Component public contract: Distinguish attributes, properties, methods, and events by how each lets the host page configure, use, or hear from a component.
Why it matters: These are the ways a page interacts with a component without relying on its internal rendering. - Component creation sequence: Trace what happens when the browser encounters a custom tag, from constructing the element through preparing its DOM and handling later changes.
Why it matters: The sequence shows where initial setup fits and that later changes can trigger callbacks.
Key terms: host element, custom tag, HTMLElement, shadow DOM tree, shadow DOM root, public interface, attributes, properties, methods, events
7.5.2 The puzzle
This section defines the main pieces of a web component and distinguishes content inside its shadow DOM from content supplied by its consumer.
- Custom element and interface: Explain that a custom element is a new HTML element defined and registered in the browser, and that its interface lets consumers set data and read data and changes.
Why it matters: It separates what the component is from how other code interacts with it. - Page and shadow DOM boundary: Distinguish the consumer’s document or page DOM from the shadow DOM inside a custom element, and identify the host element as their boundary.
Why it matters: The inside–outside distinction makes the other component terms easier to place. - Light DOM and slots: Describe light DOM as children supplied by the component’s consumer, and a slot as a placeholder inside shadow DOM that displays that content.
Why it matters: It explains how consumer-supplied children can appear in a component’s inner content. - Templates and styling parts: State that a template is inert HTML that can be cloned for each component instance, while a part names an area of the inner shadow DOM exposed for outside styling.
Why it matters: These terms distinguish reusable markup from an opening for outside styling.
Key terms: custom element, interface, Document DOM, Page DOM, Shadow DOM, host element, Light DOM, slot, part, template
7.5.3 Abilities
Lists capabilities that Web Components add beyond plain HTML, without explaining how to implement them.
- Web Component capabilities: Describe, at a high level, capabilities Web Components add beyond plain HTML, such as creating a tag, encapsulating markup and CSS, and passing data through attributes or properties.
Why it matters: This gives you a high-level picture of what Web Components can add before the book explains each ability.
Key terms: Web Components, shadow DOM, attributes, properties
7.6 Custom Elements API
Introduces what the Custom Elements API provides, the two kinds of custom elements, and how registered elements begin responding to the browser.
- Custom Elements API role: Explain how the Custom Elements API lets developers give HTML elements custom behavior and how custom elements relate to web components.
Why it matters: This distinction keeps the API’s role clear without treating every custom element as a complete web component. - Two custom element kinds: Distinguish autonomous custom elements from customised built-in custom elements, including why autonomous elements are more commonly used.
Why it matters: The distinction explains both the available element forms and the practical reason to favor autonomous elements. - Registration and initial callbacks: Describe how a custom element’s class is registered and what happens when the browser encounters and inserts its tag.
Why it matters: This sequence explains how a registered element’s code begins responding to the page.
Key terms: Custom Elements API, custom element, web component, autonomous custom elements, HTMLElement, customised built-in custom elements, is attribute, class, register, constructor
7.6.1 Creation
This section explains how to create an autonomous custom-element class, when to initialize it versus work with its DOM, and why defining the class alone does not make it usable as a custom element.
- Custom element initialization timing: Explain why an autonomous custom element extends HTMLElement and why its constructor should call super() and initialize state without reading HTML attributes or child nodes.
Why it matters: Choosing the right time to read the element prevents code from relying on DOM content that may not exist yet. - Connected callback DOM access: Describe how connectedCallback() is used to access the element's attributes and nodes, set its content, and perform DOM work through this.
Why it matters: This gives the component a place to work with its own DOM rather than doing that work too early. - Class definition versus registration: Distinguish making a custom-element class available in JavaScript from registering it with the browser for use as a custom element.
Why it matters: A defined class alone is not enough for the browser to recognize a custom element.
Key terms: autonomous elements, HTMLElement, constructor, super(), connectedCallback(), this, DOM APIs, registered, custom element
7.6.2 Rendering content
This section compares ways to render a custom element’s content and explains how to handle user-supplied content safely.
- Custom element rendering strategies: Describe the four rendering strategies named here and their basic tradeoffs: creating DOM nodes, setting innerHTML, cloning a template, or loading external HTML.
Why it matters: The rendering choice affects how you organize markup and how much control you have over creating it. - Safe user content rendering: Explain why unsanitized user input must not be inserted through innerHTML and what to use for text-only content or user-supplied HTML.
Why it matters: A shadow root does not make unsafe HTML insertion safe from injected scripts.
Key terms: Imperative DOM creation, innerHTML, HTML templates, External HTML file, shadow root, textContent, XSS, sanitize, shadow DOM, page DOM
7.6.3 Registration
Explains how to register a custom element, use it in HTML or JavaScript, and choose a valid name.
- Custom element registration: Explain that customElements.define(name, constructor) makes a custom element available to the page by associating its tag name with the class or constructor that defines it, and describe what happens if the tag is used without registration.
Why it matters: Registration is what makes a custom tag behave as your component rather than remain an ordinary empty element. - Element creation and connection: Describe using a registered custom element in HTML or JavaScript, including when its constructor and connectedCallback run and why constructor arguments are not recommended for parameterization.
Why it matters: Creation and DOM attachment are different moments, so JavaScript-created elements do not run their connection behavior immediately. - Registration timing and upgrades: Explain why the section recommends registering an element when its definition loads, and state when customElements.upgrade(container) is useful.
Why it matters: Predictable registration prevents code from trying to use a component before its definition is available. - Valid custom element names: State the principal naming constraints for a custom element and explain why the browser requires a hyphen.
Why it matters: A name that violates these rules cannot be registered, and the required hyphen keeps custom names distinct from standard ones.
Key terms: customElements.define(), constructor, HTMLElement, connectedCallback, attributes, properties, customElements.upgrade(container), module, race conditions, custom element name
7.6.4 Simplifying the syntax
This subsection shows that custom element definitions can use shorter syntax, including literal classes or a function-style helper, while distinguishing the helper from a built-in API.
- Simpler custom element syntax: Explain that a custom element can be defined with a literal class, or presented in a function-like style through a helper. Distinguish the example micro-library from actual web platform API syntax.
Why it matters: It helps you recognize a convenient wrapper without mistaking it for native custom-element syntax.
Key terms: literal classes, constructor function, simple helper, micro-library, custom element
7.6.5 The Custom Element Registry
This section introduces CustomElementRegistry helpers for checking registration, waiting for it, and upgrading elements created before registration.
- Registry access and readiness: Explain where the CustomElementRegistry is available and distinguish checking whether a custom element is registered from waiting for its registration.
Why it matters: These helpers let you check availability now or postpone work until a component is registered. - Upgrading an existing subtree: Describe what customElements.upgrade(root) does and the situation in which it can help.
Why it matters: It addresses the case where markup containing custom elements exists before their definitions are registered.
Key terms: CustomElementRegistry, customElements, get(name), whenDefined(name), customElements.upgrade(root), subtree, registration
7.7 Our first component
The section uses a counter-button example to show independent custom-element instances, then explains how their hosts can be styled and how CSS can handle elements awaiting registration.
- Independent counter button instances: Explain how multiple <counter-button> elements can reuse one component while keeping separate buttons and counter values.
Why it matters: This is the practical benefit of reusing a component rather than copying its behavior throughout a page. - Custom element host styling: Describe how a custom element participates in the CSS cascade and what styling its tag name targets.
Why it matters: It distinguishes styling the custom element’s host from the component’s other styling. - Defined and pending elements: Distinguish what :defined and :not(:defined) match and explain their use while custom elements await registration.
Why it matters: These selectors let a page handle custom tags before asynchronous registration completes without hiding built-in elements. - Connected callback on DOM moves: State when connectedCallback can fire beyond an element’s initial addition to the document.
Why it matters: A component may encounter this callback again when its element is moved.
Key terms: autonomous custom element, <counter-button>, instance, internal count, CSS cascade, host element, inline elements, :defined, :not(:defined), customElements.define()
7.8 Shadow DOM
This section explains how Shadow DOM gives web components an isolated DOM boundary and what that boundary means for styles, queries, events, and root access.
- Shadow DOM encapsulation boundary: Explain how attaching a shadow root separates a component’s internal DOM from the page DOM and why that makes custom elements less vulnerable to page CSS and JavaScript.
Why it matters: The boundary helps a component behave consistently on pages with different styles and scripts. - Other shadow boundary effects: Describe the section’s other consequences of a shadow boundary for IDs, events, and communication with the page.
Why it matters: Isolation affects more than CSS: it also shapes how the page identifies and interacts with a component. - Open and closed root access: Distinguish open and closed shadow roots in terms of programmatic access without confusing that distinction with whether page selectors cross the boundary.
Why it matters: Open does not mean that ordinary page queries or CSS can reach inside the shadow tree.
Key terms: Shadow DOM, shadow root, shadow boundary, light DOM, page DOM, IDs, events, retargeted, host element, open root
7.8.1 Creation
Explains how to attach a shadow root, render into it, and choose options that control access, focus, and slot assignment.
- Shadow root and host roles: Explain how a component creates a shadow root and why internal content is rendered through the root rather than the host element.
Why it matters: Keeping the shadow root and host distinct prevents content meant for the component’s internals from being added to its light DOM. - Open and closed shadow modes: Distinguish open and closed shadow modes by outside access to the shadow root, and explain what closed mode does not protect.
Why it matters: The mode communicates how much of a component’s internals outside code is expected to access, not a security guarantee. - Focus and slot options: Describe the effects of the delegatesFocus and slotAssignment options to attachShadow().
Why it matters: These options identify two behaviors that can be set when creating the shadow root.
Key terms: attachShadow(), ShadowRoot, this.shadowRoot, host, light DOM, mode, open, closed, host.shadowRoot, encapsulation
7.8.2 Styles with the page DOM
This section shows how a custom element that uses the page DOM shares CSS with the rest of the page, allowing styles to affect elements in both directions.
- Shared page DOM styles: Explain why styles can affect both the page and a custom element when the element does not use a shadow root, using the button and heading example.
Why it matters: It explains why a component’s appearance—or the rest of the page—may change unexpectedly.
Key terms: page DOM, shadow root, cascade
7.8.3 Styles with Shadow DOM
This section shows how attaching a shadow DOM isolates a component’s styles, how open and closed modes differ, and how :host can set the component’s display behavior.
- Shadow DOM style isolation: Explain how moving MyComponent’s innerHTML into an attached shadow DOM isolates its style declarations from global styles, and use the button and h1 example to describe the result.
Why it matters: Style isolation helps prevent a component’s CSS and the page’s CSS from having unintended effects on each other. - Open and closed shadow modes: Distinguish open and closed shadow modes in terms of access to the shadow root, while noting what does not change in this example.
Why it matters: The mode changes how code reaches the shadow root, not the visual or style-isolation result shown here. - Host display styling: Describe what :host represents and how it can be used to choose a custom component’s display behavior.
Why it matters: It gives the component a way to control how its host element participates in page layout.
Key terms: shadow DOM, innerHTML, global scope, style declarations, mode: 'open', mode: 'closed', host.shadowRoot, attachShadow(), :host, host element
7.8.4 Styling web components
This section compares ways to style web components, recommends shadow-root encapsulation, and explains how adopted stylesheets let components share parsed CSS.
- Component styling options: Describe the styling options presented: styles or external stylesheets inside a shadow root, constructible stylesheets, and page styles when there is no shadow root. Explain the loading risk of an external stylesheet.
Why it matters: The placement of CSS rules affects both styling isolation and how the component first appears. - Shadow root style encapsulation: Justify the recommendation to put styles in a shadow root except for elementary elements, and describe the risk of relying on page styles.
Why it matters: Style isolation helps a custom element remain reliable on pages whose CSS you do not control. - Shared adopted stylesheets: Explain how a constructible stylesheet is populated and adopted by a shadow root, and why sharing it differs from putting a separate <style> element in every instance.
Why it matters: Sharing a parsed sheet can avoid repeating CSS parsing across many component instances.
Key terms: shadow root, <style>, external style sheets, constructible style sheets, global styles, encapsulate styles, Adopted Stylesheets, CSSStyleSheet, replaceSync(), replace()
7.9 Element parameterization
This section introduces the ways consumers can parameterize a custom element and highlights practical distinctions and cautions when exposing its API.
- Attributes and properties: Distinguish HTML attributes from JavaScript properties as ways to pass values to a custom element. Explain which kinds of values each typically suits and why accepting values makes a component reusable.
Why it matters: Choosing an appropriate input lets consumers reuse one component with different data or behavior. - CSS-based visual customization: Explain why CSS is preferred over attributes for visual styling and describe what a consumer can customize through CSS custom properties.
Why it matters: CSS lets a component’s consumer adapt its appearance using familiar styling tools. - Attribute-property synchronization: State whether an element’s attributes and properties stay synchronized automatically and what is required if both expose the same value.
Why it matters: It prevents callers from assuming that changing one representation automatically updates the other. - Slot content placeholders: Describe the limited role of slots introduced here as a way for consumers to provide content to a custom element.
Why it matters: Slots identify a content input distinct from attributes, properties, and styling values. - Safe DOM access timing: State when a custom element can safely access the DOM instead of doing so in its constructor.
Why it matters: Waiting until the DOM is ready avoids relying on elements that may not yet exist.
Key terms: attributes, properties, getAttribute(), setAttribute(), CSS custom properties, visual styling, media queries, in sync, slots, <slot>
7.9.1 data-* vs standard attributes
Explains when a custom element should use standard attributes instead of data-* attributes and how JavaScript accesses each kind.
- Component attribute design: Distinguish core component configuration from application-specific metadata when choosing attributes. Explain why standard attributes are preferred for settings such as variant or size, while data-* attributes suit values such as product IDs or indexes.
Why it matters: This choice makes a custom element’s public API feel more like that of a built-in element. - Attribute access methods: Describe how component code accesses data-* values through dataset and standard attribute values through getAttribute and setAttribute.
Why it matters: The attribute choice determines which API the component uses to read or write its values.
Key terms: standard attributes, data attributes, core configuration, metadata, dataset API, this.dataset.attributeName, getAttribute, setAttribute
7.9.2 Boolean attributes
This subsection explains how to interpret boolean attributes on custom elements by checking whether the attribute is present.
- Boolean attribute presence: Explain that a boolean attribute is true when present and false when absent, regardless of its written value. Describe why a custom element should use hasAttribute() rather than the string returned by getAttribute() to check it.
Why it matters: A custom element can misread its own settings if it treats a boolean attribute’s text as a true-or-false value.
Key terms: boolean attributes, hasAttribute(), getAttribute(), readonly
7.9.3 Update the component while observing attributes
This section explains how a custom element notices changes to selected attributes and updates its content after initial rendering.
- Observed attribute registration: Explain how to declare which attributes a custom element observes and why an attribute must be on that list for change notifications to occur.
Why it matters: Listing an attribute is what makes later changes to it observable by the component. - Attribute change updates: Describe what attributeChangedCallback receives and how a component can use it to update its content when an observed attribute changes after initial rendering.
Why it matters: A component should reflect a consumer’s changed input rather than keep showing its initial content.
Key terms: observedAttributes, attributeChangedCallback, observed attributes, connectedCallback, render
7.9.4 Update the component observing properties
This section explains that a web component with a property-based API should update when a property changes, and introduces a setter as a way to do that.
- Property changes and component updates: Explain why a web component that exposes a property-based API should update when that property changes, and describe how a setter can provide a place to trigger the update.
Why it matters: Changing a component’s property should have an effect on the component, rather than leave its displayed state out of date.
Key terms: attributes, properties, property-based API, getters and setters, setter function
7.10 Creating a rating component
This section illustrates a registered star-rating web component whose value attribute controls how many of its five stars appear active.
- Star rating value attribute: Explain how the example star-rating component represents a rating and what <star-rating value='3'></star-rating> displays.
Why it matters: The example shows how an HTML attribute can configure what a reusable component displays.
Key terms: star-rating, value attribute, active
7.11 Working with events
The section explains how custom elements communicate through events and uses an editable star-rating component to show an event in response to user input.
- Custom element event communication: Explain how a custom element exposes an internal occurrence to consumers by dispatching a CustomEvent, and how consumers listen on the element. Describe what detail, bubbles, and composed control.
Why it matters: An event gives consumers a standard way to respond to what happens inside a component. - Editable rating event behavior: Trace the editable star-rating example from a star click to a value update and change event. Explain why changing its editable attribute after insertion does not change its behavior.
Why it matters: The example connects a user's input to an outward-facing event while showing a limit of an unobserved attribute.
Key terms: CustomEvent, dispatchEvent(), detail, bubbles, composed, addEventListener(), star-rating, editable, boolean attribute, change event
7.12 Connecting the page DOM and shadow DOM with CSS
Introduces the CSS techniques that the following subsections use to connect the page DOM and shadow DOM.
7.12.1 Read custom properties for theming
Explains how shadow-DOM components can use page-defined CSS custom properties for theming, with defaults and a reusability caution.
- Page-defined theme properties: Explain that CSS custom properties cross the shadow DOM barrier, allowing a component to use theme values defined in the page DOM without explicitly mapping or defining them inside the component.
Why it matters: This lets a page provide theme values to a component even when its styles are in shadow DOM. - Theme defaults and coupling: Describe why a component should offer a default when a theme token is unset, and why reliance on global CSS custom properties should be used with care.
Why it matters: Defaults make optional theme values safer, while limiting project-specific dependencies helps keep components reusable.
Key terms: CSS custom properties, page DOM, shadow DOM barrier, theme token, default value, global CSS custom properties, reusable
7.12.2 Expose custom properties for parametrization
This section shows how CSS custom properties let a page customize a web component’s shadow DOM styles while the component supplies defaults.
- Custom properties across shadow DOM: Explain how a component can use CSS custom properties set on its host by the page, even though ordinary page styles do not affect the shadow tree. Describe how the component uses var() and supplies defaults with :host that page-defined values can override.
Why it matters: It lets consumers customize a component without directly styling its shadow-tree elements. - Per-instance component color settings: Describe how page CSS can target all or selected custom-element instances to give them different custom-property values, as with the read-only and editable star ratings.
Why it matters: The same component can have different appearances in different contexts.
Key terms: CSS custom properties, shadow DOM, :host, var(), page DOM, CSS selector, custom elements, tokens, read-only star ratings, editable star ratings
7.12.3 Expose elements to the page DOM
This section shows how a web component can expose selected shadow DOM elements for styling from the page.
- Exposed shadow DOM parts: Explain how a component names selected shadow DOM elements with the part attribute so consumers can style them from page CSS using ::part(), without accessing the entire shadow tree.
Why it matters: Parts let a component offer specific styling hooks without requiring consumers to reach into its shadow tree. - Part names and forwarding: Describe how part names can apply to multiple elements, how an element can have multiple parts, and how a host can forward names from a nested component with exportparts.
Why it matters: These options help a component expose useful styling hooks even when its internal structure includes several elements or nested components.
Key terms: part attribute, ::part() pseudo-element, shadow DOM, exportparts attribute
7.12.4 Read state from the page DOM
This section explains how shadow DOM CSS can respond to attributes and classes set on a component’s host element in the page DOM.
- Host selector state styling: Explain how :host(selector) lets a web component style itself according to a class or attribute on its host element, and distinguish it from unconditional :host.
Why it matters: It lets a page influence a component’s styling through attributes on the component tag.
Key terms: :host, :host(selector), host element, shadow DOM, page DOM
7.13 Summary
Where this is used later
- Using web components in frameworks (chapter 9) · Using web components in frameworks draws on their independence from any one framework.
- Form participation (chapter 9) · Form participation is an example of a feature for which support may need attention.
- Data binding techniques (chapter 13) · Data binding techniques address reactive UI work that this section identifies as difficult.
- Using Templates in Web Components (chapter 8) · Uses templates in web components.
- Element internals (chapter 9) · Develops Element Internals.
- Web components lifecycle (chapter 9) · Expands on the component lifecycle.
- Using Slots (chapter 8) · Using slots depends on knowing where light-DOM content comes from and where slots sit.
- Using external HTML files (chapter 8) · Creating web components with the Custom Elements API.
Concepts explained in this chapter
- Custom ElementsA developer-defined HTML element registered through the browser's custom element APIs with custom behavior and lifecycle callbacks.
- Web ComponentsA reusable custom HTML element built using browser standards such as custom elements, shadow DOM, and HTML templates.
- connectedcallbackconnectedCallback is a custom element lifecycle callback that the browser invokes when the element is attached to a document DOM.
- Shadow DOMShadow DOM is a web platform feature for attaching an encapsulated DOM tree to an element.
- shadow rootA shadow root is the encapsulated DOM subtree attached to a shadow host for implementing a web component's internal structure and presentation.
- customElements.defineA browser method that registers a custom element name with its constructor and optional built-in-element extension options.
- componentA self-contained software unit designed for use in multiple parts of an application or across applications.
- shadow hostThe element to which a shadow root is attached and which represents the component externally.
- attributeA JavaScript property is a named value associated with an object.
- CustomElementRegistryThe browser registry interface for defining and retrieving custom element constructors.
- attachShadowAn Element method that creates and attaches a shadow root with the requested mode.
- constructor methodA JavaScript function intended to create and initialize object instances when invoked as a constructor.
- CSS variableA CSS custom property is an author-defined property whose value can be inherited and reused in CSS declarations through the var() function.
- light DOMThe DOM content supplied by a web component's host document rather than contained in the component's shadow tree.
- HTML template elementThe HTML <template> element holds inert markup that can later be cloned and inserted into a document or shadow DOM.
- apiAn API surface is the set of interfaces and operations that software exposes for external use.
- CustomEventA script-created DOM event that can carry application-specific data and participate in event propagation.
- slot elementThe HTML <slot> element defines an insertion point for content projected into a web component's shadow tree.
- interoperabilityInteroperability is the ability of software systems or components to exchange and use information correctly across their boundaries.
- cascadeThe CSS cascade is the rule system that resolves competing style declarations according to origin, importance, specificity, and source order.
- custom element lifecycleA method invoked by the browser when a custom element is connected, disconnected, adopted, or has an observed attribute changed.
- constructable stylesheetA constructible stylesheet is a programmatically created CSSStyleSheet that can be adopted and shared by document or shadow roots.
- Document Object ModelThe browser programming interface for querying and manipulating a document's DOM representation.
- addEventListeneraddEventListener is a DOM API method that registers a callback for events of a specified type on an event target.
- dispatchEventdispatchEvent is a DOM API method that synchronously dispatches an event to an object and its event listeners.
- ElementInternalsElementInternals is a browser interface that provides a custom element with access to internal capabilities such as form participation and accessibility semantics.
- textContenttextContent is a DOM node property that gets or sets the plain text content of a node and its descendants without parsing markup.
- reactive programmingReactivity is a programming model in which changes to data automatically propagate to dependent computations or interface output.
- data attributeA custom HTML attribute whose name begins with data- and whose value stores application-specific information on an element.
- datasetA DOM property that exposes an element’s data-* attributes through a camelCase-keyed object of string values.
- customElementsThe browser global property that provides access to a CustomElementRegistry instance.
- renderingRendering is the process of producing visible interface content from application data, state, or route information.
- HTMLElement APIHTMLElement is the base browser interface implemented by most concrete HTML element objects and their shared properties and methods.
- form-associated custom elementA form-associated custom element is a custom HTML element that participates in a form's association, disabled-state, reset, and state-restoration behavior.
- micro-libraryA small software library providing narrowly scoped functionality.
- lazy initializationA technique that defers loading or initialization until content or functionality is needed.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
