1.一次性全部渲染
<script>
const total = 100000;
let oContainer = document.getElementById("container");
for(let i = 0; i < total; i++){
let oLi = document.createElement("li");
oLi.innerHTML = i;
oContainer.appendChild(oLi);
}
</script>
当然这样一次性全部渲染服务器的性能消耗太大,肯定是不可取的,所以我们选择分批加载
2.定时器分批加载
<script>
const total = 100000;
let oContainer = document.getElementById("container");
const once = 2000;
const index = 0;
function insert(curTotal, curIndex) {
if (curTotal < 0) {
return;
}
setTimeout(() => {
for(let i = 0; i<once; i++) {
let oLi = document.createElement("li");
oLi.innerHTML = i + curIndex;
oContainer.appendChild(oLi);
}
insert(curTotal - once,curIndex + once);
},0)
}
insert(total, index)
</script>
setTimeout(()=> {},100)定时器的时间并不是固定,若前面的事件在事件内还没执行完,后面的事件要等到前面的事件执行结束。
3.window.requestAnimationFrame()
: 根据屏幕的FPS刷新网页
<script>
const total = 100000;
let oContainer = document.getElementById("container");
const once = 2000;
const index = 0;
function insert(curTotal, curIndex) {
if (curTotal < 0) {
return;
}
window.requestAnimationFrame(() => {
for(let i = 0; i < once; i++) {
let oLi = document.createElement("li");
oLi.innerHTML = i + curIndex;
oContainer.appendChild(oLi);
}
insert(curTotal - once,curIndex + once);
})
}
insert(total, index)
</script>
但是这样每次进行for循环的时候都会向dom中添加li,改变了dom结构,这样就会导致浏览器的回流,影响浏览器的性能,为了降低性能我们可以用文档碎片。
4 .documentFragment()文档碎片
: 减少浏览器的回流
<script>
const total = 100000;
let oContainer = document.getElementById("container");
const once = 2000;
const index = 0;
function insert(curTotal, curIndex) {
if (curTotal < 0) {
return;
}
window.requestAnimationFrame(() => {
let fragment = document.createDocumentFragment();//文档碎片
for (let i = 0; i < once; i++) {
let oLi = document.createElement("li");
oLi.innerHTML = i + curIndex;
fragment.appendChild(oLi);
}
oContainer.appendChild(fragment)
insert(curTotal - once, curIndex + once);
})
}
insert(total, index)
</script>
这样会大大提升浏览器的性能。
最后
- 文章为作者学习笔记分享,如有错误欢迎大家指正,希望文章能对你有所帮助
- 写的不好还请见谅,也欢迎各位大佬找我一起学习,一起进步
- 加油!!!