createDocumentFragment()
1、创建虚拟节点,在创建之初是空的
2、createDocumentFragment本身不属于文档流,插入节点时,它本身不插入节点,是它的所有子孙节点即括号中的内容插入节点,相当于一个占位符。
3、当需要添加多个dom元素时,先将元素放入createDocumentFragment中,会减少渲染次数,提高性能。
requestAnimationFrame()
requestAnimationFrame比起setTimeout和setInterVal的优势主要有两点:
1、requestAnimationFrame会把一帧中所有dom操作集中起来,在一次重回和回流中完成,并且重回和回流的时间间隔紧紧跟随浏览器的书信频率。
2、在隐藏和不可见元素中,requestAnimationFrame将不会进行重回和回流,这就减少了内存使用提高性能了。
<body>
<ul></ul>
<script>
// 总共需要渲染的数据条数
const total = 100000;
// 每次渲染的条数
const once = 10;
// 插入数据需要的次数
const countLoop = Math.ceil(total / once)
// 渲染的次数
let countRender = 0;
// 获取插入的父节点
const ul = document.querySelector('ul');
// 添加数据的方法
const add = () => {
// 创建虚拟节点
const fragment = document.createDocumentFragment();
for (let i = 0; i < once; i++) {
const li = document.createElement('li')
li.innerHTML = `这是第${countRender}插入产生的随机数:${Math.floor(Math.random()*total)}`;
fragment.appendChild(li);
}
ul.appendChild(fragment);
countRender++;
loop();
}
const loop = () => {
if (countRender < countLoop) {
window.requestAnimationFrame(add)
}
}
loop()
</script>
</body>