如何将10万条数据渲染到页面做到不卡顿
window.requestAnimationFrame(callback) (请求动画帧)
callback:下一次重绘之前更新动画帧所调用的函数(即上面所说的回调函数)。
作用:告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行
document.createdocumentfragment() (创建虚拟节点)
作用:创建了一虚拟的节点对象,节点对象包含所有属性和方法。减少添加dom的次数。
示例代码:循环10万次,并在每次执行的时候给页面添加一个“li”标签内容为随机数。
说明:如果一次性循环完成10万次,因为每次循环都存在dom的添加,js代码又是阻塞式的,其他任务得不到执行,那么浏览器必定就会出现卡顿。解决方法也就是在一定时间段后执行一次添加,每次添加20条。给予其他任务执行的空间。requestAnimationFrame该方法传入的函数,浏览器会在每次重绘页面的时候,调用该函数。
<!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>
<ul></ul>
<script>
/*
createDocumentFragment 创建虚拟节点
requestAnimationFrame 请求动画帧
*/
// 总数
const total = 100000;
// 每次插入20条
const once = 20;
// 插入的次数
const loopCount = Math.ceil(total / once);
// 渲染的次数
let countRender = 0;
// 获取插入的父节点
const ul = document.querySelector('ul');
// 添加数据的方法1 此方法更优
function add() {
// 创建虚拟节点
const fragment = document.createDocumentFragment()
for (let i = 0; i < once; i++) {
const li = document.createElement('li');
li.innerHTML = Math.floor(Math.random() * 100000)
fragment.appendChild(li)
}
ul.appendChild(fragment);
countRender++;
loop();
}
/* // 添加数据的方法2
function add() {
for (let i = 0; i < once; i++) {
const li = document.createElement('li');
li.innerHTML = Math.floor(Math.random() * 100000)
ul.appendChild(li);
}
countRender++;
loop();
}*/
function loop() {
if (countRender < loopCount) {
// 未超过渲染次数
window.requestAnimationFrame(add);
}
// if (countRender >= loopCount) {
// return;
// }
}
loop()
</script>
</body>
</html>
动画帧
<!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>
<style>
.box {
width: 100px;
height: 100px;
background-color: #ccc;
position: absolute;
left: 0;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var left = 0;
var flag = true;
var box = document.querySelector('.box');
function rendrs() {
if (flag == true) {
if (left >= 100) {
flag = false;
}
box.style.left = left++ + 'px'
}
if (flag == false) {
if (left <= 0) {
flag = true;
}
box.style.left = left-- + 'px'
}
}
(function loop() {
rendrs();
requestAnimationFrame(loop)
})()
</script>
</body>
</html>