概述`<template>` 提供可克隆的离屏内容;`DocumentFragment` 作为轻量容器用于批量插入,避免多次重排。两者结合实现高效渲染。示例<template id="item">
<li class="item"><span class="title"></span></li>
</template>
<ul id="list"></ul>
<script>
const tpl = document.getElementById('item')
const frag = document.createDocumentFragment()
for (const t of ['A','B','C']) {
const node = tpl.content.cloneNode(true)
node.querySelector('.title').textContent = t
frag.append(node)
}
document.getElementById('list').append(frag)
</script>
工程建议批量操作:尽量在 Fragment 中构建并一次性插入;减少布局抖动。组件化:配合自定义元素与 Shadow DOM;提高可维护性与封装。兼容:在旧环境回退到字符串模板与 `innerHTML`;防止 XSS。参考与验证MDN `<template>` 文档:https://developer.mozilla.org/docs/Web/HTML/Element/templateMDN DocumentFragment 文档:https://developer.mozilla.org/docs/Web/API/DocumentFragment

发表评论 取消回复