HTML <template> 元素是浏览器原生支持的惰性模板机制,不渲染、不执行脚本、不加载资源,仅通过 JavaScript 克隆插入 DOM,具备防 XSS、语义清晰、支持 Shadow DOM 等优势。

HTML <template> 元素是浏览器原生支持的轻量级模板机制,不参与渲染、不执行脚本、不加载资源,只在需要时通过 JavaScript 克隆并插入 DOM,特别适合动态渲染场景。
template 的核心特性与优势
它被设计为“惰性容器”:页面加载时,<template> 内容不会被解析、不触发图片加载、不运行内联脚本、也不影响 CSS 作用域。这避免了传统字符串拼接模板或提前渲染带来的性能和安全问题。
- 内容默认不可见,
content属性提供只读的 DocumentFragment 接口 - 支持任意合法 HTML 结构(含表单、自定义元素、slot 等)
- 天然防 XSS:直接
innerHTML插入用户数据仍有风险,而 template +textContent或受控属性赋值更安全 - 比手动创建元素更语义清晰,比 innerHTML 更易维护结构逻辑
基础用法:克隆、填充、挂载
典型流程是:获取 template → 克隆 content → 修改其中内容 → 插入目标容器。
- 用
document.getElementById()或querySelector()获取 template 元素 - 调用
content.cloneNode(true)得到可操作的副本(避免重复使用同一 fragment) - 对副本中的元素设置
textContent、value、dataset等,或用querySelector定位后更新 - 用
appendChild()或append()插入到真实 DOM 中
例如渲染用户列表项:
立即学习“Java免费学习笔记(深入)”;
<template id="user-item"><li class="user">
<span class="name"></span>
<span class="email"></span>
</li>
</template>
JS 中:
const tmpl = document.querySelector('#user-item');const frag = tmpl.content.cloneNode(true);
frag.querySelector('.name').textContent = '张三';
frag.querySelector('.email').textContent = 'zhang@example.com';
listEl.append(frag);
结合事件与交互的注意事项
template 内部绑定的事件监听器不会自动生效,因为克隆后是全新节点;内联 onclick 也不会执行(template 不解析脚本)。正确做法是:
- 在克隆后的元素上显式添加事件监听器(推荐)
- 利用事件委托,在父容器监听,通过
event.target.matches()判断来源 - 避免在 template 中写内联 JS,保持结构与行为分离
若需复用逻辑,可封装为函数,接收数据与 fragment 副本,统一处理填充和绑定。
进阶技巧:配合自定义元素与 Shadow DOM
template 是定义 Web Components 的标准载体。在 customElements.define() 中,常将 template 作为 shadow root 的初始内容:
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
this.shadowRoot.querySelector('.name').textContent = this.getAttribute('name');
}
}
此时 template 不仅提升复用性,还天然隔离样式与逻辑,适合构建可嵌入的动态 UI 组件。











