template标签不渲染但需正确放置于body或head下,内容藏在只读content属性中,必须clonenode(true)克隆后插入dom,且需手动初始化表单值和事件,ie完全不支持。

template 标签本身不渲染,但必须放对位置、用对方式,否则克隆后仍是空的或结构错乱。
template 必须是 或 的直接子元素
浏览器会强制修正非法嵌套,比如写在 <table> 里、<code><script></script> 标签内,或自闭合标签(如 @@##@@)之后——内容会被挪出甚至丢弃。
- ✅ 正确:
<template id="item"><li>...</li></template> - ❌ 错误:
<table><template><tr><td>x</td></tr></template></table>→<template></template>被提到<table> 外,<code><tr> 变成孤儿节点 <li>❌ 错误:<code><script><template>...</script>→ 解析失败,template.content为空 - ❌
container.appendChild(template)→ 插入的是空标签,无内容 - ❌
container.appendChild(template.content)→ 第二次调用就失效(fragment 已被移走) - ✅
container.appendChild(template.content.cloneNode(true))→ 每次都深克隆,保留全部嵌套结构 - ⚠️
cloneNode(false)只克隆顶层容器,内部元素全丢失,必须加true - 手动设值:
clone.querySelector('input').value = data.name - 手动绑定事件:
clone.querySelector('.save-btn').addEventListener('click', saveHandler) - 避免用
id:模板中写id="email"→ 克隆多次后 ID 重复,改用class或data-id -
<slot></slot>可用,但需配合 Shadow DOM 和slot属性,普通页面中基本无效 - 真正容易被忽略的一点:
template连 CSS 都不应用,哪怕里面写了<style></style>;图片、字体、iframe 一律不加载;连display: none都不是,它根本不在 DOM 树里 - 服务端渲染时,
template会被原样输出,客户端 JS 必须等DOMContentLoaded后再访问content - 大量渲染时,建议先批量克隆进一个临时
DocumentFragment,再一次性appendChild,减少重排重绘
必须用 template.content.cloneNode(true) 才能插入真实 DOM
template 元素自己没有子节点,template.children 是空的,template.innerHTML 永远返回空字符串。所有内容都藏在只读的 content 属性里,它是一个 DocumentFragment,只能被插入一次。
克隆后要手动初始化表单值和事件
template 里的 <input>、<select></select>、<textarea></textarea> 克隆后只保留 HTML 中定义的初始 value 或 checked,不会继承用户输入;内联 onclick 不生效,<script></script> 不执行,<img> 不发请求。
IE 完全不支持,且惰性比你想象得更彻底
Edge 13+、Chrome 26+、Firefox 22+、Safari 7.1+ 支持良好,但 IE 无任何 polyfill 能完全模拟 content 的 DocumentFragment 行为——必须降级为字符串模板或服务端预渲染。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











