之前在工作中有出现过因为页面要一次性加载大量数据导致页面卡顿的情况,当时没想到解决的方法也就错过了,昨晚在b站看视频时发现了解决的办法,所有搬运下来,避免忘记,以后复用。
html代码
<ul id="ul">
</ul>
需要用到两个原生的方法:
Document.createDocumentFragment() MDN文档链接;
window.requestAnimationFrame();MDN文档链接
//要加载的数据数量
const total = 50000;
//一次加载的数据量
const once = 30;
const loopCount = Math.ceil(total/once);
let countRender = 0;
const ul = document.getElementById('ul');
function add(){
const fragment = document.createDocumentFragment();
for(let i = 0;i< once;i++){
let li = document.createElement('li');
li.innerHTML= Math.floor(Math.random()*100000);
fragment.appendChild(li);
}
ul.appendChild(fragment);
countRender++;
loop()
}
function loop(){
if(countRender <loopCount){
window.requestAnimationFrame(add)
}
}
loop()