Slot Fallback Content
What you'll learn: How to provide default content inside <slot> tags that appears automatically when no external content is slotted in.
The Core Idea
Think of slot fallback content as the "placeholder text" of Web Components. When you define a <slot> in your Shadow DOM, you can put content inside the slot element itself. This content only displays if the component's user doesn't provide anything to fill that slot.
It's like a restaurant menu with a daily special: if the chef doesn't specify today's special (Light DOM content), the menu automatically shows "Chef's Surprise" (fallback content). The fallback disappears the moment real content is slotted in.
How It Works
Inside your Shadow DOM template, place default content between the opening and closing <slot> tags:
class ProfileCard extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<div class="card">
<h2><slot name="username">Anonymous User</slot></h2>
<p><slot name="bio">No bio provided.</slot></p>
<slot>Welcome to my profile!</slot>
</div>
`;
}
}
customElements.define('profile-card', ProfileCard);
If you use it without providing content:
<profile-card></profile-card>
You'll see all three fallback messages. But if you provide content:
<profile-card>
<span slot="username">Jane Developer</span>
</profile-card>
Only the username slot gets replaced—the bio and default slot still show their fallbacks.
Key Takeaway: Slot fallback content provides graceful defaults that automatically hide when users supply their own content, making your Web Components more robust and user-friendly.