Web Components
Intermediate Course Chapter 11 introduced the core concept — a custom element with a shadow root. This chapter completes the picture: the full lifecycle a custom element actually goes through, building it properly with <template> instead of a string literal, and <slot> for letting users place their own content inside your component.
The Full Custom Element Lifecycle
| Callback | Fires when |
|---|---|
| constructor() | The element instance is created — too early to safely read attributes or children yet |
| connectedCallback() | The element is actually inserted into the document (Intermediate Ch11) — the safe place to read attributes and build initial content |
| disconnectedCallback() | The element is removed from the document — clean up event listeners, timers, subscriptions here |
| attributeChangedCallback(name, old, new) | A watched attribute's value changes — only fires for attributes explicitly listed in observedAttributes |
observedAttributes array means changes to it are silently ignored — the callback never fires for anything not in that list. A genuinely common first mistake when building a component that's supposed to react to attribute changes.
Using template with Shadow DOM — The Cleaner Pattern
Intermediate Chapter 11's example built shadow DOM content via a string template literal. A real component typically uses an actual <template> element (Intermediate Chapter 8) instead — genuine, validatable HTML rather than a string.
slot — Letting Users Pass Their Own Content In
Without slots, a custom element's content is entirely fixed by its own internal template — there's no way for someone using the component to insert their own content into it. <slot> creates a placeholder the user's own light-DOM content gets projected into.
Named Slots — Multiple Insertion Points
Chapter 1 Quick Reference
- Full lifecycle: constructor → connectedCallback → attributeChangedCallback (repeatable) → disconnectedCallback
- observedAttributes must explicitly list every attribute that should trigger attributeChangedCallback
- Build shadow content from a real <template>, cloned via cloneNode(true), rather than a string literal
- <slot> — a placeholder for user-supplied light-DOM content to be projected into the shadow root
- Named slots (slot="name") — multiple distinct insertion points within one component
- Slotted content keeps light-DOM styling — a deliberate exception to shadow DOM's otherwise strict encapsulation
- Next chapter: Canvas API basics — drawing, animation fundamentals