文章目录
- 1. 描述
- 2. 使用
1. 描述
DocumentFragments 是DOM节点。通常的用例是创建文档片段,将元素附加到文档片段,然后将文档片段附加到DOM树。在DOM树中,文档片段被其所有的子元素所代替。
因为文档片段存在于内存中,并不在DOM树中,所以将子元素插入到文档片段时不会引起页面回流(对元素位置和几何上的计算)。因此,使用文档片段通常会带来更好的性能。
减少页面重绘
2. 使用
例: 修改所有li的内容
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head>
<body><ul><li> test1 </li><li> test2 </li><li> test3 </li></ul><script>const ul = document.getElementsByTagName('ul')[0];const li = document.getElementsByTagName('li');// 创建fragmentconst fragment = document.createDocumentFragment();// 取出所有li到fragment[...li].forEach(li=>{fragment.appendChild(li)});// 更新fragment里所有li的文本[...fragment.children].forEach(li=>{li.innerText = 'baidu'});// 将fragment插入ulul.appendChild(fragment)</script>
</body>
</html>