Shadow DOM skeleton
Learn the HTML side of Shadow DOM (slot, template).
What is the shadow DOM?
Shadow DOM isolates a component's inner structure from the outer page. Its CSS and HTML do not feel outside rules; outer styles do not leak in. The component becomes a self-contained box.
On the HTML side, shadow DOM is usually prepared inside a <template>. JavaScript takes that template, attaches a shadow root to the component and pours the content in. Slot and template are the skeleton of shadow DOM.
Shadow skeleton with template
The content of a shadow DOM is usually written inside a <template>. The template holds <style>, <div> and <slot>. JavaScript takes the template, attaches a shadow root to the component and copies the content in.
This makes both writing and performance easier. You write the skeleton once; every component instance shares the same structure. Slots route outside content to the right place.
open and closed modes
A shadow root attaches in one of two modes: open or closed. In open mode, outside JavaScript can reach into the component's inner structure. In closed mode, that access is blocked; the component is fully sealed.
Most components use open; it makes debugging and testing easier. Closed mode is reserved for sensitive components like payment forms, where the inner structure must stay hidden.
Exercise Write the shadow skeleton inside a template
Add a <template> to body. Inside it put a <style> (content: p { color: gray; }), a <p> (text: Description), and a <slot>.
Show example solution
<body>
<template>
<style>p { color: gray; }</style>
<p>Description</p>
<slot></slot>
</template>
</body>
Test yourself
-
What is the main benefit of the shadow DOM?
- It shortens page load time.
- It reduces JavaScript dependency.
- It works on old browsers too.
- It isolates the component's inner structure from the page.
Show answer
It isolates the component's inner structure from the page. — Correct. Shadow DOM isolates the component's inner structure.
-
Complete the shadow DOM definition
The mechanism that isolates a component's inner structure is: ____ DOMShow answer
The mechanism that isolates a component's inner structure is: shadow DOM -
Match the shadow DOM terms
- shadow DOM
- inner structure isolation
- shadow root
- node content attaches to
- template
- skeleton template
- slot
- where content lands