What is Shadow DOM
What is Shadow DOM?
Shadow DOM is a core part of the Web Components standard, allowing developers to encapsulate HTML, CSS, and JavaScript within a custom element. This encapsulation ensures that styles and behavior inside the component are isolated from the rest of the document, preventing conflicts between internal and external CSS or scripts.
How It Works
- Shadow Root: A shadow DOM is created inside a host element by attaching a shadow root, which acts as a separate document tree.
- Encapsulation: Elements within the shadow DOM don’t interfere with or inherit styles from the main DOM (unless explicitly designed to do so).
- Slots: The shadow DOM allows for content projection through
<slot>
elements, letting external content be placed inside the component.
Example of Shadow DOM in Action
<custom-element></custom-element>
<script>
class CustomElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
p { color: red; }
</style>
<p>This is inside the shadow DOM</p>
`;
}
}
customElements.define('custom-element', CustomElement);
</script>
In this example, the <p>
element inside the shadow DOM will remain unaffected by CSS from the main document. Even if the main page defines a different style for <p>
elements, it won’t apply inside the shadow tree.
Modes of Shadow DOM
- Open Mode: The shadow root is accessible through JavaScript with
element.shadowRoot
. - Closed Mode: The shadow root is hidden from external scripts.
Use Cases for Shadow DOM
- Web Components: Encapsulate reusable UI elements like modals, buttons, or dropdowns.
- Style Isolation: Prevent style leakage between a component and the main page.
- Browser UI Elements: Native elements like
<video>
and<input>
use shadow DOM internally to structure their content and styles.
Limitations of Shadow DOM
- Selectors like querySelector can’t access it directly: You need to explicitly traverse the shadow root or use utilities like Puppeteer’s
pierce
selector. - SEO Challenges: Content inside shadow DOM might not always be indexed properly by search engines.
Shadow DOM helps in building modular and maintainable code, making it an essential tool for modern web development【19†source】【20†source】.
댓글
댓글 쓰기