---
title: Declarative Shadow DOM:SSR 组件封装与样式隔离
keywords:
- Declarative Shadow DOM
- shadowrootmode
- 样式隔离
- SSR
description: 介绍声明式 Shadow DOM 的模板语法、SSR 下的组件封装与样式隔离、与自定义元素协作及兼容回退策略,提供示例与权威参考。
categories:
- 文章资讯
- 编程技术
---
概述
Declarative Shadow DOM 允许在 HTML 中通过 <template shadowrootmode> 声明组件的 Shadow 根,适合在 SSR 中输出可直接渲染的组件结构,与样式与插槽隔离更稳定。
示例
<div class="card">
<template shadowrootmode="open">
<style>.title{font-weight:600}</style>
<slot name="title" class="title"></slot>
<slot name="content"></slot>
</template>
<span slot="title">标题</span>
<p slot="content">正文</p>
<script type="module">
customElements.define('x-card', class extends HTMLElement {})
</script>
</div>
工程建议
- SSR 输出:在服务器生成包含声明式 Shadow 的 HTML;前端增强时与自定义元素协作。
- 样式隔离:在 Shadow 中定义样式避免外部干扰;使用 Slots 组织内容。
- 兼容:不支持浏览器回退到常规 DOM 或脚本注入 Shadow;特性检测后启用。
参考与验证
- Chrome 平台文档(Declarative Shadow DOM):https://developer.chrome.com/docs/web-platform/declarative-shadow-dom/
- web.dev 指南:https://web.dev/articles/declarative-shadow-dom
- WHATWG/讨论:https://github.com/whatwg/html/pull/4697

发表评论 取消回复