后端给你1W条数据,怎么保证前端在渲染的时候页面不会卡

document.createDocumentFragment()
用来创建一个虚拟的节点对象,节点对象不属于文档树。
当需要添加多个DOM元素时,可以先把DOM添加到这个虚拟节点中。然后再统一将虚拟节点添加到页面,这会减少页面渲染DOM的次数。

window.requestAnimationFrame
接受参数为函数,比起setTimeout和setInterval有以下优点:
1.把每一帧中的所有DOM操作集中起来,在一次的重排/重绘中完成。每秒60帧。
2.在隐藏或者不可见的元素中,requestAnimationFrame将不会重绘/重排。

具体实现代码

//总数据
const total = 10000;
//每次插入的数据
const once = 20;
//需要插入的次数
const times = Math.ceil(total/once)
//当前插入的次数
const curTimes = 0;
//需要插入的位置
const ul = document.querySelector('ul')
function add(){
    
    
	let frag = document.createDocumetFragment()
	for(let i = 0;i<once;i++){
    
    
	let li = document.createElement('li')
	li.innerHTML = Math.floor(i+curTimes*once)
	frag.appendChild(li)
	}
	curTimes++;
	ul.appendChild(frag)
	if(curTimes<times){
    
    
	window.requestAnimationFrag(add)
	}
}
	window.requestAnimationFrag(add)

猜你喜欢

转载自blog.csdn.net/qq_56392992/article/details/124388978