<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--
如何渲染几万条数据并不卡住页面
这道题考察了如何在不卡住页面的情况下渲染数据,也就是说不能一次性将几万都渲染出来,而应该一次渲染部分DOM,那么就可以通过requestAnimationFrame来每16m刷新一次
-->
<ul>控件</ul>
<script>
setTimeout(()=>{
const total = 100000;
const once = 20;
const loopCount = total / once;
let countOfRender = 0;
let ul = document.querySelector('ul');
function add(){
const fragment = document.createDocumentFragment();
for(let i = 0; i< once; i++){
const li = document.createElement('li')
li.innerText = i;
fragment.appendChild(li);
}
ul.appendChild(fragment);
countOfRender += 1;
loop();
}
function loop(){
if(countOfRender < loopCount){
window.requestAnimationFrame(add);
}
}
loop()
},0)
</script>
</body>
</html>