Chapter 9: Advanced web components
This introduction previews advanced web component topics aimed at making components more like native controls, easier to integrate, and simpler to ship.
After this chapter you will be able to
- ElementInternals browser capabilities. Explain why a custom control may need ElementInternals even if it already renders and responds to events. Describe the form, validation, and accessibility capabilities it makes available.
- Enabling form participation. State the two class-level steps given for enabling form participation in a custom element.
- Submitting the component value. Explain what setFormValue() does for a form-associated custom element.
- ElementInternals validation methods. Distinguish how setValidity(), checkValidity(), and reportValidity() set, check, and report a custom element’s validity.
- ElementInternals form context properties. Explain what the read-only ElementInternals properties form, labels, and willValidate tell a component, and when inspecting them can help it adapt its behavior.
- Importance of lifecycle timing. Explain why the timing of custom element callbacks matters during an element’s lifetime.
- Custom element lifecycle callbacks. Describe when the constructor, connectedCallback, attributeChangedCallback, disconnectedCallback, and adoptedCallback run, including that connection and disconnection can happen more than once.
- Early attribute change guards. Explain why attributeChangedCallback can run before connectedCallback and how to guard DOM work that depends on the element being connected.
- Adoption and connection callbacks. Explain that adoptedCallback() runs when a custom element moves to a different document, while connectedCallback() also runs if the adopted element is later inserted into that document.
- Form-associated lifecycle callbacks. Describe when each of the four form-associated callbacks runs: association or disassociation with a form, a disabled-state change, a form reset, or restoration of user state or form-fill data.
- Submission and restoration values. Explain how setFormValue() can keep a submitted value separate from the state later supplied to formStateRestoreCallback(), and why a richer control might need that distinction.
- Disconnected component cleanup. Explain that disconnectedCallback() is where a component releases resources it owns, including timers, pending fetches, observers, and global listeners.
- Shared AbortController teardown. Describe how using one AbortController for a global listener and a fetch makes teardown explicit and helps avoid forgetting part of the cleanup.
- Custom element registration checks. Distinguish using customElements.whenDefined() to wait for a tag’s registration from using customElements.get() for a synchronous existence check.
- Pre-upgrade component styling. Explain how :defined and :not(:defined) can style custom elements before and after registration, and why hiding an unupgraded element may be inappropriate when it contains critical content.
- Custom element semantics. Explain why a web component that looks like a familiar control does not automatically have that control’s native semantics.
- Native elements before ElementInternals. Describe the section’s preferred choice for accessible controls and when ElementInternals is useful.
- Default ARIA semantics through internals. Explain how a component can set its role and ARIA properties through ElementInternals, and why this is usually preferable to setting ARIA attributes directly on the page.
- ARIA semantics versus behavior. Distinguish what setting ariaDisabled communicates from what the component must do to prevent activation.
- Appropriate ARIA property selection. Explain that ElementInternals exposes many ARIA reflection properties, but a custom widget should use only the properties that truly describe it.
- Accessible switch behavior. Describe the capabilities of the example toggle switch: it uses the switch role, exposes checked and disabled states, responds to click, Enter, and Space, and participates in forms.
- Accessible focus and keyboard behavior. Explain why ARIA alone does not make an interactive custom element accessible, and describe the focus and keyboard questions its design must answer.
- Shadow-root focus delegation. Explain that delegatesFocus can direct focus from a component host to the first focusable descendant in its shadow tree, which is useful for field-like components. Distinguish this help from the explicit keyboard behavior still needed by complex widgets.
- Dialog focus handoff. Describe how a modal dialog saves the previously focused element, moves focus into the dialog when it opens, and restores focus when it closes.
- Standard control activation keys. Explain why web components should follow established widget keyboard conventions, including how buttons, checkboxes, and switches respond to keys.
- Composite widget keyboard patterns. Describe the expected keyboard behavior for radio groups, tabs, menus, and dialogs.
- Custom states in CSS. Explain how CustomStateSet lets an autonomous custom element expose internal states to CSS through :state(), and why this is useful compared with mirroring those states as attributes or classes.
- Custom state set management. Describe how to access and change a custom element’s state set, and explain what must happen if its states need to be exclusive.
- Attributes versus custom states. Distinguish when to represent a state with a host attribute and when to use a custom state.
- Host state styling with CSS. Explain that CSS can select a custom element with :state() when the state is present in its state set, then combine that selector with ::part() to style a part based on the host’s state.
- Internal button states. Explain why the example exposes loading, success, and error as custom states rather than publishing them in the host element’s visible markup.
- Declarative shadow root creation. Explain how Declarative Shadow DOM uses a <template> with a shadowrootmode attribute to create a shadow root during HTML parsing, and why this is useful before component JavaScript loads.
- Shadow root creation timing. Explain that the browser creates a declarative shadow root while parsing the markup, before the component class upgrades, so the initial render need not wait for JavaScript.
- Choosing Declarative Shadow DOM. Explain why Declarative Shadow DOM suits server-rendered or static HTML that should render before component JavaScript loads, and why attachShadow() is usually enough for a component created entirely on the client.
- Existing shadow root reuse. Explain why hydration should reuse an existing declarative shadow root and call attachShadow() only when no root exists.
- Prehydration visibility and interaction. Explain why a declarative shadow root should remain visible before its custom element is registered, and how :defined can help limit interaction until hydration finishes.
- Declarative focus delegation. Explain what shadowrootdelegatesfocus does and when it is useful for a field-like component.
- Clonable declarative shadow roots. Describe what shadowrootclonable permits when a node is cloned or imported, and where that is useful.
- Serializable declarative shadow roots. Explain what shadowrootserializable permits with getHTML() and who is most likely to need it.
- Declarative shadow resource loading. Explain that a declarative shadow root is real DOM, so its images and external stylesheets begin loading when parsed, unlike resources in an inert template that wait until cloning. Describe how this lets server-rendered shadow content render and load resources before the component class hydrates.
- Real-browser testing environment. Explain why a real browser makes web component tests more trustworthy, even though web components can be tested with many tools.
- Three testing layers. Distinguish unit, integration, and visual regression tests by what each checks in a web component.
- Browser test page basics. Describe how a simple HTML page can test a component by loading it, running assertions, and reporting failures in the console.
- Open shadow root queries. Explain how a test can access internal nodes in a component with an open shadow root.
- Direct slot assignment checks. Describe what a test should inspect to verify slot content, including content assigned to a default slot.
- Form-associated component tests. Explain why form-associated custom elements need explicit submission and validation tests, and describe how a validation test can check the result.
- Visual testing coverage gaps. Explain why screenshot-based tests complement logic tests for components with multiple states, especially interactive components.
- Cross-framework component interoperability. Explain why web components can be used in React, Angular, Vue, and other libraries without those libraries needing to know their internal implementation.
- Basic framework integration rules. State the basic rules for using a web component in a framework: register it before using its tag, pass simple strings through attributes and complex values through properties, and receive communication through events.
- Cross framework component interface. Distinguish the recommended uses of attributes, properties, and custom events when a framework hosts a custom element.
- React component wrapper direction. Explain that a React component can be wrapped inside a custom element so a page that does not use React can use it.
- Angular custom element bridge. Explain that @angular/elements provides Angular’s official bridge: createCustomElement() turns an Angular component into a custom element, which is then registered.
- Vue custom-element integration. Explain that Vue 3’s defineCustomElement() returns a native custom-element constructor, and describe how Vue custom elements expose emitted events and styles to the web platform.
- Web component distribution decisions. Explain why building a web component is not enough and describe the distribution questions to settle: how people load it in plain HTML or a bundler-based app, whether import paths remain stable, and how the element is registered.
- Standalone ES module distribution. Explain how a standalone ES module lets consumers use a web component: importing the browser-ready module registers the element as a side effect, enabling direct use with little adoption friction.
- Preserving element registration. Explain why package metadata must protect a module whose purpose is to register a custom element from tree-shaking.
- CDN-ready component delivery. Explain how publishing a browser-ready ESM file through npm lets developers try a component without installing it: they can load it from a CDN such as unpkg or jsDelivr, or import it by URL from another module.
- Optional bundling benefits. Explain that web components do not require bundling, but a bundler can help optimize published files, provide different output formats, and support older targets.
- Discoverable component entry and usage. Describe how to make a distributed component straightforward to find and try: register it from one documented entry module, use a stable hyphenated custom-element name, provide a plain HTML example, and expose clear package entry points.
- Stable distribution and public API. Explain the checklist's maintenance-facing advice: keep CDN paths stable across versions, use semantic versioning, and document the component's public attributes, properties, events, CSS custom properties, and parts.
What it builds on
- Creation (chapter 7) · Creating custom elements as HTMLElement subclasses.
- Update the component while observing attributes (chapter 7) · Assumes familiarity with observing attributes.
- Registration (chapter 7) · Custom elements must be registered under a tag name.
- Creation (chapter 7) · Attaching a shadow root to a component.
- Modal dialogs (chapter 3) · The earlier introduction to modal dialogs.
- Element parameterization (chapter 7) · Element parameterization introduces attributes as a way to expose component settings.
- Fallback Content (chapter 8) · A slot can provide fallback content.
- The Need for Cloning Templates (chapter 8) · The distinction between inert template content and content activated by cloning.
Section by section
Introduction
This introduction previews advanced web component topics aimed at making components more like native controls, easier to integrate, and simpler to ship.
9.1 Element internals
This section introduces ElementInternals as the way custom elements gain access to browser features they do not receive automatically.
- ElementInternals browser capabilities: Explain why a custom control may need ElementInternals even if it already renders and responds to events. Describe the form, validation, and accessibility capabilities it makes available.
Why it matters: Rendering a control is not enough to give it native form-field behavior. - Attaching and retaining internals: Describe where attachInternals() is called and what the component does with its return value.
Why it matters: Keeping the returned object lets the component use these browser features later.
Key terms: ElementInternals, form participation, constraint validation, default accessibility semantics, attachInternals(), constructor
9.1.1 Form participation
This section explains what form participation gives a custom element, how to enable it, and how to include its value in form submission.
- Form participation capabilities: Describe how a form-associated custom element can behave like a native form control, including validation, resets, disabled-state changes, and label association.
Why it matters: These capabilities explain why form participation is useful beyond submitting a value. - Enabling form participation: State the two class-level steps given for enabling form participation in a custom element.
Why it matters: Both steps are the starting point for making the custom element form-associated. - Submitting the component value: Explain what setFormValue() does for a form-associated custom element.
Why it matters: This is the connection between the component's value and ordinary form submission.
Key terms: form-associated custom element, constraint validation, form resets, disabled state, <label>, static formAssociated = true, attachInternals(), constructor, ElementInternals, setFormValue()
9.1.2 Validation methods
This section explains how ElementInternals gives form-associated custom elements native-like validation behavior.
- ElementInternals validation methods: Distinguish how setValidity(), checkValidity(), and reportValidity() set, check, and report a custom element’s validity.
Why it matters: These methods let a custom element participate in validation like a native form control. - Native-like validation benefit: Explain why native-like validation favors a form-associated custom element over a widget that merely looks like a field.
Why it matters: A field-like appearance alone does not provide the native-like validation described here.
Key terms: ElementInternals, setValidity(), checkValidity(), reportValidity(), flags, invalid, native-like validation, form-associated custom elements, native form controls
9.1.3 Accessing form and labels
This subsection explains how a web component can inspect its form context through ElementInternals properties.
- ElementInternals form context properties: Explain what the read-only ElementInternals properties form, labels, and willValidate tell a component, and when inspecting them can help it adapt its behavior.
Why it matters: These properties let a component adjust to its form context rather than assume it always has the same form or labels.
Key terms: ElementInternals, form, labels, willValidate, connectedCallback(), constraint validation
9.2 Web components lifecycle
The section introduces custom elements as having lifecycle phases and explains why callback timing matters before the detailed lifecycle discussion.
- Importance of lifecycle timing: Explain why the timing of custom element callbacks matters during an element’s lifetime.
Why it matters: Callback timing helps you avoid common bugs as a custom element moves through its lifecycle.
Key terms: custom element, callback, lifetime
9.2.1 Basic lifecycle flow
This section identifies the main custom-element lifecycle callbacks and explains why attribute-change handling may need a connection guard.
- Custom element lifecycle callbacks: Describe when the constructor, connectedCallback, attributeChangedCallback, disconnectedCallback, and adoptedCallback run, including that connection and disconnection can happen more than once.
Why it matters: These callbacks let a component respond to the different events in its lifetime. - Early attribute change guards: Explain why attributeChangedCallback can run before connectedCallback and how to guard DOM work that depends on the element being connected.
Why it matters: This prevents attribute-driven rendering from assuming the element is already connected.
Key terms: constructor(), connectedCallback(), attributeChangedCallback(), disconnectedCallback(), adoptedCallback(), isConnected, upgrade, internally initialized flag
9.2.2 The adoptedCallback() in practice
Explains when adoptedCallback() runs, how it differs from connection in the target document, and when a component needs it.
- Adoption and connection callbacks: Explain that adoptedCallback() runs when a custom element moves to a different document, while connectedCallback() also runs if the adopted element is later inserted into that document.
Why it matters: Moving an element between documents and inserting it into one are distinct lifecycle events. - Document scoped reference refresh: Describe why a component might use adoptedCallback() to refresh cached references after moving between documents.
Why it matters: A cached reference to the old document's objects may no longer be appropriate after adoption.
Key terms: adoptedCallback(), connectedCallback(), adoption, document-scoped objects, document, window
9.2.3 Form-associated lifecycle
This section identifies the four additional lifecycle callbacks of form-associated custom elements and explains why they help keep component state aligned with form behavior.
- Form-associated lifecycle callbacks: Describe when each of the four form-associated callbacks runs: association or disassociation with a form, a disabled-state change, a form reset, or restoration of user state or form-fill data.
Why it matters: These callbacks tell a component when form behavior may require it to update its own state. - Internal state and form behavior: Explain why the callbacks are especially useful for a component whose internal state is richer than a single string.
Why it matters: A component may need to coordinate more than one simple value with changes in its form.
Key terms: formAssociatedCallback(form), formDisabledCallback(disabled), formResetCallback(), formStateRestoreCallback(state, mode), internal state, form behavior
9.2.4 Restoring form state after navigation
This section explains why a form-associated component may store a restoration state separately from the value it submits.
- Submission and restoration values: Explain how setFormValue() can keep a submitted value separate from the state later supplied to formStateRestoreCallback(), and why a richer control might need that distinction.
Why it matters: A rich control can submit a compact value without losing the information needed to restore its user-facing state.
Key terms: setFormValue(), formStateRestoreCallback(state, mode), submission value, restoration state, FormData
9.2.5 Cleanup in disconnectedCallback()
This section explains what a component should clean up when disconnected and how one AbortController can simplify part of that teardown.
- Disconnected component cleanup: Explain that disconnectedCallback() is where a component releases resources it owns, including timers, pending fetches, observers, and global listeners.
Why it matters: Putting cleanup in the disconnection callback gives owned resources a clear teardown point. - Shared AbortController teardown: Describe how using one AbortController for a global listener and a fetch makes teardown explicit and helps avoid forgetting part of the cleanup.
Why it matters: Grouping related teardown makes it less likely that one resource will be forgotten.
Key terms: disconnectedCallback(), timers, pending fetches, observers, global listeners, AbortController, global listener, fetch, teardown
9.2.6 Waiting for element registration
This section shows how to wait for a custom element to be registered or check its registration synchronously.
- Custom element registration checks: Distinguish using customElements.whenDefined() to wait for a tag’s registration from using customElements.get() for a synchronous existence check.
Why it matters: Choosing the right check lets application code coordinate with a custom element that may not be registered yet.
Key terms: customElements.whenDefined(), customElements.get(), registered
9.2.7 Styling undefined elements with :defined
This section explains how CSS can style custom elements before they are defined, and why hiding them during that time requires care.
- Pre-upgrade component styling: Explain how :defined and :not(:defined) can style custom elements before and after registration, and why hiding an unupgraded element may be inappropriate when it contains critical content.
Why it matters: A server-rendered component may appear before its JavaScript loads, so its pre-upgrade styling affects what readers can see.
Key terms: :defined, :not(:defined), unupgraded elements
9.3 Advanced accessibility for web components
This section explains why custom elements need explicit accessibility semantics and recommends native elements first, with ElementInternals as a way to define defaults when needed.
- Custom element semantics: Explain why a web component that looks like a familiar control does not automatically have that control’s native semantics.
Why it matters: A control’s appearance alone does not tell the browser what it is. - Native elements before ElementInternals: Describe the section’s preferred choice for accessible controls and when ElementInternals is useful.
Why it matters: This gives you a simple first choice and a fallback for custom controls.
Key terms: custom element, native semantics, generic host, native element, ElementInternals, default ARIA semantics, host element
9.3.1 ARIA via ElementInternals
This subsection shows how a web component can set default accessibility semantics through ElementInternals while still implementing the behavior those semantics describe.
- Default ARIA semantics through internals: Explain how a component can set its role and ARIA properties through ElementInternals, and why this is usually preferable to setting ARIA attributes directly on the page.
Why it matters: Keeping default semantics in the component makes its accessibility contract part of the component itself. - ARIA semantics versus behavior: Distinguish what setting ariaDisabled communicates from what the component must do to prevent activation.
Why it matters: An accessible state must agree with what the component actually does.
Key terms: ElementInternals, ARIA reflection properties, role, ariaDisabled, semantics, behavior, assistive technology
9.3.2 Common ARIA properties
This section notes that ElementInternals exposes ARIA properties for custom widgets and advises setting only those that accurately describe the widget.
- Appropriate ARIA property selection: Explain that ElementInternals exposes many ARIA reflection properties, but a custom widget should use only the properties that truly describe it.
Why it matters: Accurate ARIA properties help describe a widget without assigning it characteristics it does not have.
Key terms: ElementInternals, ARIA reflection properties, custom widgets
9.3.3 Building an accessible toggle
This section describes an accessible toggle-switch example that combines switch semantics, keyboard interaction, form participation, and a public attribute for styling.
- Accessible switch behavior: Describe the capabilities of the example toggle switch: it uses the switch role, exposes checked and disabled states, responds to click, Enter, and Space, and participates in forms.
Why it matters: An accessible switch needs more than a visual on/off appearance. - Public checked styling attribute: Explain why the example uses its public checked attribute as both an API and a styling hook rather than using aria-checked for CSS.
Why it matters: It keeps the component’s public styling hook distinct from its ARIA semantics.
Key terms: role="switch", checked, disabled, form participation, public checked attribute, aria-checked, styling hook
9.4 Focus and keyboard management
The section establishes that accessible interactive web components need deliberate focus and keyboard behavior, not just ARIA.
- Accessible focus and keyboard behavior: Explain why ARIA alone does not make an interactive custom element accessible, and describe the focus and keyboard questions its design must answer.
Why it matters: These questions help reveal whether people can actually operate the component with a keyboard.
Key terms: ARIA, focus, keyboard behavior, custom element
9.4.1 Delegating focus into shadow DOM
This subsection explains how delegatesFocus directs focus into a shadow tree and why it does not replace keyboard behavior for complex widgets.
- Shadow-root focus delegation: Explain that delegatesFocus can direct focus from a component host to the first focusable descendant in its shadow tree, which is useful for field-like components. Distinguish this help from the explicit keyboard behavior still needed by complex widgets.
Why it matters: It helps a component put focus on its visible control without mistaking that behavior for complete keyboard support.
Key terms: delegatesFocus, shadow root, host, focusable descendant
9.4.2 Managing focus programmatically
Explains how an opening and closing component should manage focus, using a modal dialog as the example, and when to prefer native <dialog>.
- Dialog focus handoff: Describe how a modal dialog saves the previously focused element, moves focus into the dialog when it opens, and restores focus when it closes.
Why it matters: Restoring focus returns the user to where they were before the dialog opened. - Native dialog preference: Explain when to use native <dialog> instead of recreating dialog behavior in a custom component.
Why it matters: It helps you avoid rebuilding dialog behavior without a specific need.
Key terms: focus, modal dialog, previously focused element, native <dialog>, custom dialog component
9.4.3 Keyboard interaction patterns
This section sets out established keyboard conventions for web components and recommends modern keyboard event handling.
- Standard control activation keys: Explain why web components should follow established widget keyboard conventions, including how buttons, checkboxes, and switches respond to keys.
Why it matters: Familiar keyboard behavior makes a component usable beyond its visual appearance. - Composite widget keyboard patterns: Describe the expected keyboard behavior for radio groups, tabs, menus, and dialogs.
Why it matters: Matching each widget’s expected pattern helps keyboard users operate it predictably. - Modern keyboard event handling: State which keyboard events to listen for in a component and which older event pattern to avoid.
Why it matters: Choosing the recommended events avoids relying on a deprecated keyboard pattern.
Key terms: widget conventions, WAI-ARIA Authoring Practices Guide, Enter, Space, radio groups, tabs, menus, dialogs, arrow keys, Escape
9.5 Custom state set
Introduces CustomStateSet as a way for autonomous custom elements to expose internal states to CSS without mirroring them as attributes or classes.
- Custom states in CSS: Explain how CustomStateSet lets an autonomous custom element expose internal states to CSS through :state(), and why this is useful compared with mirroring those states as attributes or classes.
Why it matters: It gives a component a way to make its state available for styling without exposing every internal detail as an attribute or class.
Key terms: CustomStateSet, autonomous custom elements, :state() pseudo-class, internal states
9.5.1 The states property
Explains how to manage custom states through ElementInternals.states and when to use them instead of host attributes.
- Custom state set management: Describe how to access and change a custom element’s state set, and explain what must happen if its states need to be exclusive.
Why it matters: Managing the state set correctly prevents a component from retaining conflicting states. - Attributes versus custom states: Distinguish when to represent a state with a host attribute and when to use a custom state.
Why it matters: This distinction helps keep public component settings separate from internal styling state.
Key terms: ElementInternals.states, add(), delete(), has(), custom states, host attributes, public API
9.5.2 The :state() pseudo-class
This section explains how CSS selects a custom element’s state and uses that selection to style its parts.
- Host state styling with CSS: Explain that CSS can select a custom element with :state() when the state is present in its state set, then combine that selector with ::part() to style a part based on the host’s state.
Why it matters: It helps you put the state selector on the right element when styling a component’s parts.
Key terms: :state(), ::part(), custom element, host, state
9.5.3 Building a stateful component
Illustrates a stateful button whose internal states can affect styling without appearing in the host element’s markup.
- Internal button states: Explain why the example exposes loading, success, and error as custom states rather than publishing them in the host element’s visible markup.
Why it matters: This explains when custom states are useful for component styling. - Consumer example and button text: Describe what the consumer example demonstrates when it calls saveData, and how its button text differs from the template’s default.
Why it matters: The example connects the button’s states and slot fallback to what a consumer sees.
Key terms: CustomStateSet, custom states, host element, saveData, loading, success, <slot>, Save Changes, Submit
9.6 Declarative Shadow DOM
Introduces how Declarative Shadow DOM creates shadow content from HTML during parsing and why that helps server-rendered or static pages.
- Declarative shadow root creation: Explain how Declarative Shadow DOM uses a <template> with a shadowrootmode attribute to create a shadow root during HTML parsing, and why this is useful before component JavaScript loads.
Why it matters: You can include shadow content in HTML rather than waiting for component JavaScript to create it.
Key terms: Declarative Shadow DOM, DSD, <template>, shadowrootmode, shadow root, host
9.6.1 Basic syntax
This subsection explains that declarative shadow roots are created during HTML parsing, before a component upgrades, and identifies the standardized attribute name.
- Shadow root creation timing: Explain that the browser creates a declarative shadow root while parsing the markup, before the component class upgrades, so the initial render need not wait for JavaScript.
Why it matters: This explains why a component can show its initial content before its JavaScript runs. - Standard shadow root attribute: Distinguish the current standardized shadowrootmode attribute from the older Chrome-only shadowroot attribute.
Why it matters: It helps you avoid copying outdated syntax from older examples.
Key terms: declarative shadow root, component class upgrades, initial render, shadowrootmode, shadowroot
9.6.2 When to use Declarative Shadow DOM
This section explains when Declarative Shadow DOM is useful and when creating a shadow root in JavaScript is sufficient.
- Choosing Declarative Shadow DOM: Explain why Declarative Shadow DOM suits server-rendered or static HTML that should render before component JavaScript loads, and why attachShadow() is usually enough for a component created entirely on the client.
Why it matters: The rendering model, not a preference for newer APIs, determines whether DSD is useful.
Key terms: Declarative Shadow DOM, DSD, server-side rendering, static site generation, progressive enhancement, attachShadow()
9.6.3 Hydrating a declarative shadow root
Explains how to hydrate a declarative shadow root without destroying server-rendered content, including how to access roots in open and closed mode.
- Existing shadow root reuse: Explain why hydration should reuse an existing declarative shadow root and call attachShadow() only when no root exists.
Why it matters: Reusing the root preserves the content already rendered into it. - Open and closed root access: Distinguish attachInternals().shadowRoot from this.shadowRoot when accessing a declarative shadow root during hydration.
Why it matters: The choice of root accessor determines whether the pattern still works with a closed root.
Key terms: hydration, declarative shadow root, attachShadow(), server-rendered content, attachInternals().shadowRoot, this.shadowRoot, open, closed
9.6.4 Using CSS with DSD before hydration
Explains how to keep a declarative shadow root visible before hydration while limiting interaction until the custom element is ready.
- Prehydration visibility and interaction: Explain why a declarative shadow root should remain visible before its custom element is registered, and how :defined can help limit interaction until hydration finishes.
Why it matters: Users can see server-rendered content before the component becomes interactive.
Key terms: declarative shadow root, :defined, hydration, display: none
9.6.5 DSD configuration attributes
Explains three attributes that configure focus delegation, cloning, and serialization for declarative shadow roots.
- Declarative focus delegation: Explain what shadowrootdelegatesfocus does and when it is useful for a field-like component.
Why it matters: It helps a custom field behave as users expect when they click it. - Clonable declarative shadow roots: Describe what shadowrootclonable permits when a node is cloned or imported, and where that is useful.
Why it matters: It identifies when copying a node can also copy its declarative shadow root. - Serializable declarative shadow roots: Explain what shadowrootserializable permits with getHTML() and who is most likely to need it.
Why it matters: It distinguishes including a shadow root in serialized HTML from copying it during cloning.
Key terms: shadowrootdelegatesfocus, focus delegation, host, shadow tree, shadowrootclonable, cloneNode(true), importNode(), shadowrootserializable, getHTML(), serialization
9.6.6 Resource loading in declarative shadow roots
This section explains when resources load in declarative shadow roots, how that differs from ordinary templates, and why it helps server-side rendering.
- Declarative shadow resource loading: Explain that a declarative shadow root is real DOM, so its images and external stylesheets begin loading when parsed, unlike resources in an inert template that wait until cloning. Describe how this lets server-rendered shadow content render and load resources before the component class hydrates.
Why it matters: This explains a resource-loading advantage of declarative shadow DOM for server-side rendering. - Stylesheets in shadow roots: State that declarative shadow roots support both inline and external stylesheets, and that the browser efficiently loads and parses identical external stylesheets referenced by multiple such roots.
Why it matters: Repeated use of an external stylesheet across declarative shadow roots does not imply wasteful repeated loading and parsing.
Key terms: declarative shadow root, inert <template>, SSR, hydrates, inline and external stylesheets, declarative shadow roots
9.7 Testing web components
This section explains why web components are best tested in a real browser and introduces three complementary layers of testing.
- Real-browser testing environment: Explain why a real browser makes web component tests more trustworthy, even though web components can be tested with many tools.
Why it matters: The test environment affects how confidently you can assess browser-provided component behavior. - Three testing layers: Distinguish unit, integration, and visual regression tests by what each checks in a web component.
Why it matters: The three layers help you describe what a component test is checking.
Key terms: real browser, customElements, shadow DOM, slot distribution, form association, unit tests, integration tests, visual regression tests
9.7.1 A simple browser-based test page
This section introduces a simple browser test page for a custom element and explains when to move to an automated browser runner.
- Browser test page basics: Describe how a simple HTML page can test a component by loading it, running assertions, and reporting failures in the console.
Why it matters: It gives you a starting point for testing components in the environment where they run. - Automated browser runner choice: Explain why a manual test page is useful for exploration but real projects often use an automated browser runner.
Why it matters: It helps you choose between a quick exploratory page and repeatable project testing.
Key terms: test harness, assertions, runTests(), automated browser runner, Web Test Runner, Playwright, CI, shadow DOM
9.7.2 Testing shadow DOM and slots
This section explains how to test open-shadow components and verify slot assignments directly.
- Open shadow root queries: Explain how a test can access internal nodes in a component with an open shadow root.
Why it matters: An open shadow root does not make a component’s internals untestable. - Direct slot assignment checks: Describe what a test should inspect to verify slot content, including content assigned to a default slot.
Why it matters: Direct assignment checks test what the slot received rather than what its markup appears to imply.
Key terms: Shadow DOM, shadowRoot, open-shadow components, slots, assigned nodes, assigned elements, default slots, outer HTML
9.7.3 Testing form-associated components
This subsection identifies submission and validation as the behaviors to test in form-associated custom elements.
- Form-associated component tests: Explain why form-associated custom elements need explicit submission and validation tests, and describe how a validation test can check the result.
Why it matters: These tests check whether the component delivers the form behavior it was built to provide.
Key terms: form-associated custom elements, submission, validation, checkValidity(), reportValidity(), validity state
9.7.4 Visual regression testing
This section explains when screenshot-based tests help web components and how to keep visual regression tests useful.
- Visual testing coverage gaps: Explain why screenshot-based tests complement logic tests for components with multiple states, especially interactive components.
Why it matters: A component can behave correctly while still looking wrong in a way users notice. - Focused screenshot state selection: Describe which component states are worth capturing and why their setup should be stable and focused.
Why it matters: Stable, focused screenshots make visual changes easier to distinguish from test noise.
Key terms: logic tests, screenshot-based testing, spacing regressions, missing outlines, theme breakage, stable states, visual regression tests, state setup
9.8 Library integration
Explains why web components can be used across frameworks and states the basic rules for integrating them.
- Cross-framework component interoperability: Explain why web components can be used in React, Angular, Vue, and other libraries without those libraries needing to know their internal implementation.
Why it matters: This is why the same component can fit into applications built with different libraries. - Basic framework integration rules: State the basic rules for using a web component in a framework: register it before using its tag, pass simple strings through attributes and complex values through properties, and receive communication through events.
Why it matters: These rules give you a starting point for using a component regardless of the surrounding framework.
Key terms: web components, HTML elements, custom element, attributes, properties, native or custom events
9.8.1 Using web components in frameworks
This section explains how React, Angular, and Vue use custom elements and how to pass data and receive events across the framework boundary.
- Framework custom element usage: Describe how React, Angular, and Vue can render custom element tags, including the compilation configuration Angular and Vue may need.
Why it matters: It helps you use a custom element in a framework template without mistaking a compiler configuration issue for a component issue. - Cross framework component interface: Distinguish the recommended uses of attributes, properties, and custom events when a framework hosts a custom element.
Why it matters: This rule gives the host a straightforward way to send data in and receive messages back. - React custom element support: Explain what React 19 supports for custom-element properties and events, and why a ref remains the safest way to pass a complex object.
Why it matters: It clarifies what React 19 handles directly and when to use a ref instead.
Key terms: custom element tags, CUSTOM_ELEMENTS_SCHEMA, dashed tags, attributes, properties, custom events, React 19, ref, on… props
9.8.2 Wrapping React components as web components
This section explains that a React component can be exposed to non-React pages through a custom element and notes when a small wrapper may need a helper layer.
- React component wrapper direction: Explain that a React component can be wrapped inside a custom element so a page that does not use React can use it.
Why it matters: It shows how an existing React component can be made available outside a React application. - Wrapper size and helper layer: Distinguish the section's advice for small wrappers from its advice for larger libraries, including what a helper layer would centralize.
Why it matters: It helps you judge when a one-off wrapper may become cumbersome across a larger library.
Key terms: React, custom element, custom element host, helper layer, prop mapping, event forwarding
9.8.3 Wrapping Angular components as web components
This subsection shows how Angular components become custom elements and how their inputs, outputs, and tag names behave.
- Angular custom element bridge: Explain that @angular/elements provides Angular’s official bridge: createCustomElement() turns an Angular component into a custom element, which is then registered.
Why it matters: This is the basic route for using an Angular component as a web component. - Angular element interface and naming: Describe how Angular inputs and outputs appear on the custom element, and explain why its tag name should differ from the Angular component selector.
Why it matters: These mappings define how the custom element is used, while a distinct tag name avoids a documented pitfall.
Key terms: @angular/elements, createCustomElement(), custom element, inputs, dash-cased attributes, outputs, custom events, component selector, double-instantiation
9.8.4 Wrapping Vue components as web components
This subsection explains how Vue 3 components become native custom elements and when the runtime cost of that approach is worthwhile.
- Vue custom-element integration: Explain that Vue 3’s defineCustomElement() returns a native custom-element constructor, and describe how Vue custom elements expose emitted events and styles to the web platform.
Why it matters: It shows which parts of a Vue component remain usable through standard web-component APIs. - Custom-element runtime cost: Justify when Vue’s custom-element path may or may not be worth its runtime size cost.
Why it matters: The size tradeoff helps you decide whether a Vue wrapper fits what you are shipping.
Key terms: defineCustomElement(), native custom-element constructor, CustomEvent, shadow root, runtime size cost, component library
9.9 Deploying web components
The section frames deployment as part of building a web component and identifies the questions its distribution plan should answer.
- Web component distribution decisions: Explain why building a web component is not enough and describe the distribution questions to settle: how people load it in plain HTML or a bundler-based app, whether import paths remain stable, and how the element is registered.
Why it matters: A component is easier to adopt when consumers know how to load it and what to expect from its imports and registration.
Key terms: distribution story, import paths, side effect, registered
9.9.1 Shipping a standalone ES module
This section presents a browser-ready ES module as a simple, low-friction way to distribute a web component.
- Standalone ES module distribution: Explain how a standalone ES module lets consumers use a web component: importing the browser-ready module registers the element as a side effect, enabling direct use with little adoption friction.
Why it matters: Consumers can adopt the component without a separate registration step.
Key terms: browser-ready ES module, side effect, registers the element, adoption friction
9.9.2 Publishing as an npm package
This section explains how to package web components for bundler-based applications without losing element registration or obscuring import options.
- Preserving element registration: Explain why package metadata must protect a module whose purpose is to register a custom element from tree-shaking.
Why it matters: Otherwise, an application may import the package without the custom element being registered. - Public package entry points: Describe the import entry points the section recommends for npm packages containing one or multiple components.
Why it matters: Clear entry points let consumers choose how to import the components they need.
Key terms: sideEffects, tree-shake, register the custom element, package metadata, root entry point, per-component entry points
9.9.3 Offering a CDN-friendly build
This section explains how a browser-ready ESM build lets developers try a web component through a CDN and why its public URL must remain stable.
- CDN-ready component delivery: Explain how publishing a browser-ready ESM file through npm lets developers try a component without installing it: they can load it from a CDN such as unpkg or jsDelivr, or import it by URL from another module.
Why it matters: Developers can try your component without first adding it to their project. - Stable CDN paths: Explain why a published CDN URL should retain a stable public path once users may have pasted it into their pages.
Why it matters: Changing a public path can affect pages that use the pasted URL.
Key terms: CDN-friendly ESM builds, browser-ready file, unpkg, jsDelivr, stable public paths, external contract, CDN URL
9.9.4 Bundling and transpiling
Explains why a web component package might use bundling and why its public entry points must remain easy to find.
- Optional bundling benefits: Explain that web components do not require bundling, but a bundler can help optimize published files, provide different output formats, and support older targets.
Why it matters: You can choose a build process for a distribution need without treating it as a prerequisite for web components. - Clear public entry points: Justify keeping a bundled package's public entry points clear and documented so consumers can load an element without understanding its build system.
Why it matters: A straightforward entry point lets consumers use an element without investigating how its files were built.
Key terms: bundling, transpiling, ESM, CommonJS, public entry points, bundler
9.9.5 Distribution checklist
This section gives a pre-publish checklist for making a web component easy to try, install, and maintain.
- Discoverable component entry and usage: Describe how to make a distributed component straightforward to find and try: register it from one documented entry module, use a stable hyphenated custom-element name, provide a plain HTML example, and expose clear package entry points.
Why it matters: Clear entry points and an example make the component easier to install and try. - Stable distribution and public API: Explain the checklist's maintenance-facing advice: keep CDN paths stable across versions, use semantic versioning, and document the component's public attributes, properties, events, CSS custom properties, and parts.
Why it matters: The checklist aims to prevent avoidable support work after publication.
Key terms: entry module, custom-element name, plain HTML usage example, package entry points, package.json, CDN paths, semantic versioning, public attributes, properties, events
9.10 Summary
Where this is used later
- EventTarget stores (chapter 13) · Assumes the custom-element lifecycle and cleanup in disconnectedCallback().
- Web components (chapter 15) · Lifecycle cleanup in disconnectedCallback().
- Choosing a binding pattern (chapter 13) · Custom states exposed through the states property.
Concepts explained in this chapter
- ElementInternalsElementInternals is a browser interface that provides a custom element with access to internal capabilities such as form participation and accessibility semantics.
- declarative shadow rootAn HTML feature for declaring a shadow root and its contents in markup rather than creating them with JavaScript.
- custom element lifecycleA method invoked by the browser when a custom element is connected, disconnected, adopted, or has an observed attribute changed.
- connectedcallbackconnectedCallback is a custom element lifecycle callback that the browser invokes when the element is attached to a document DOM.
- Custom ElementsA developer-defined HTML element registered through the browser's custom element APIs with custom behavior and lifecycle callbacks.
- 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.
- attributeA JavaScript property is a named value associated with an object.
- Web ComponentsA reusable custom HTML element built using browser standards such as custom elements, shadow DOM, and HTML templates.
- ECMAScript moduleAn ECMAScript module is a separately scoped JavaScript module with explicit import and export bindings.
- constructor methodA JavaScript function intended to create and initialize object instances when invoked as a constructor.
- CustomEventA script-created DOM event that can carry application-specific data and participate in event propagation.
- attachShadowAn Element method that creates and attaches a shadow root with the requested mode.
- shadow rootA shadow root is the encapsulated DOM subtree attached to a shadow host for implementing a web component's internal structure and presentation.
- Shadow DOMShadow DOM is a web platform feature for attaching an encapsulated DOM tree to an element.
- CSS variableA CSS custom property is an author-defined property whose value can be inherited and reused in CSS declarations through the var() function.
- moduleA module is a self-contained unit of code that encapsulates declarations and can expose selected bindings to other code.
- slot elementThe HTML <slot> element defines an insertion point for content projected into a web component's shadow tree.
- AbortControllerAbortController is a browser interface for signaling cancellation of asynchronous operations such as fetch requests and event listeners.
- accessibilityThe degree to which a product or service can be used by people with varied abilities and disabilities.
- stateData representing an application's current condition and behavior.
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.
