2025.9.30
2025/12/30 20:56:02
DocumentFragment API 是 Web API 的一部分,表示一个没有父级的最小文档对象,被视为轻量版的 Document,用于存储一组 DOM 节点的集合。它不直接参与文档的渲染,因此对其操作不会触发页面的重排(reflow)或重绘(repaint),直到其内容被插入到真实 DOM 中。
constfragment=document.createDocumentFragment();for(leti=0;i<100;i++){constdiv=document.createElement('div');div.textContent=`Item${i}`;fragment.appendChild(div);}document.body.appendChild(fragment);// 仅触发一次重排constfragment=document.createDocumentFragment();constdata=[{name:'Alice'},{name:'Bob'}];data.forEach(item=>{constp=document.createElement('p');p.textContent=item.name;fragment.appendChild(p);});document.getElementById('container').appendChild(fragment);<template>标签的 content 属性返回一个 DocumentFragment,用于封装可复用的组件模板。<templateid="user-card"><divclass="card"><h3></h3><p></p></div></template><script>consttemplate=document.getElementById('user-card');constfragment=template.content.cloneNode(true);// 克隆模板内容fragment.querySelector('h3').textContent='Alice';fragment.querySelector('p').textContent='Developer';document.body.appendChild(fragment);</script>constoldNode=document.getElementById('old');constfragment=document.createDocumentFragment();fragment.appendChild(oldNode);// 移动节点到碎片document.getElementById('new-container').appendChild(fragment);functionrenderTable(data){constfragment=document.createDocumentFragment();data.forEach(row=>{consttr=document.createElement('tr');row.forEach(cell=>{consttd=document.createElement('td');td.textContent=cell;tr.appendChild(td);});fragment.appendChild(tr);});document.querySelector('table tbody').appendChild(fragment);}// 触发100次重排for(leti=0;i<100;i++){constdiv=document.createElement('div');div.textContent=`Item${i}`;document.body.appendChild(div);}// 仅触发1次重排constfragment=document.createDocumentFragment();for(leti=0;i<100;i++){constdiv=document.createElement('div');div.textContent=`Item${i}`;fragment.appendChild(div);}document.body.appendChild(fragment);DocumentFragment 是优化 DOM 操作的利器,尤其适合以下场景:
通过减少重排/重绘次数,它能显著提升页面性能,尤其在数据量大或频繁更新的场景下效果更明显。