JS高性能渲染十万条数据

330 阅读3分钟

做一个总结和学习跟大家分享,希望对大家也有所帮助,共同成长进步💪~
如果大家喜欢,可以点赞或留言哈💕~~~~,谢谢大家⭐️⭐️⭐️~~~

第一种暴力形式

<ul id="container"></ul>
const total = 100000;//插入数据的总数
let oContainer = document.getElementById("container");
for (var i = 0; i < total; i++) {
   //创建li元素
   let oLi = document.createElement("li")
   oLi.innerHTML = i; // 注意innerHTML和innerText的区别 一个是元素,一个是字符串内容
   oContainer.appendChild(oLi)
}

总结 这种通常不会采用,性能非常不好

第二种定时器分批加载形式

const total = 100000;//插入数据的总数
let oContainer = document.getElementById("container");
const once = 2000;  //一次插入的条数
const page = total / once; //总的页数
const index = 0;
function insert(curTotal,curIndex) {
   //怎样一直执行呢,可以使用递归,递归一定要有个出口,否则就死里边了
   if(curTotal<=0){
       return ''
   }
   setTimeout(() => {
       for (var i = 0; i < once; i++) {
           let oLi = document.createElement("li")
           oLi.innerHTML = curIndex + i;
           oContainer.appendChild(oLi)
       }
       insert(curTotal - once,curIndex + once)
   }, 0);//100这个时间并不是准确的,因为event loop 
}
insert(total,index) 

总结 定时器时间不太好掌握,因为event loop 运行机制,还有就是有可能会出现闪烁白屏现象

第三种动画requestAnimationFrame 形式

// 针对setTimeout问题使用requestAnimationFrame方法,性能上有些提高
const total = 100000;//插入数据的总数
let oContainer = document.getElementById("container");
const once = 2000;  //一次插入的条数
const page = total / once; //总的页数
const index = 0;
function insert(curTotal,curIndex) {
    //怎样一直执行,使用递归,递归一定要有个出口,否则就死里边了
    if(curTotal<=0){
        return ''
    }
    window.requestAnimationFrame(() => {
        let fragment = document.createDocumentFragment();//文档碎片
        for (var i = 0; i < once; i++) {
            let oLi = document.createElement("li")
            oLi.innerHTML = curIndex + i;
            oContainer.appendChild(oLi)
        }
        insert(curTotal - once,curIndex + once)
    });
}
insert(total,index) 

总结:针对setTimeout问题使用requestAnimationFrame方法,在性能上有些提高

第四种动画createDocumentFragment 形式

// 根据创建li元素,频繁的触发了重排、重绘,所以使用createDocumentFragment方法来实现避免从而提高性能
const total = 100000;//插入数据的总数
let oContainer = document.getElementById("container");
const once = 2000;  //一次插入的条数
const page = total / once; //总的页数
const index = 0;
function insert(curTotal,curIndex) {
    //怎样一直执行,使用递归,递归一定要有个出口,否则就死里边了
    if(curTotal<=0){
        return ''
    }
    window.requestAnimationFrame(() => {
        let fragment = document.createDocumentFragment();//文档碎片
        for (var i = 0; i < once; i++) {
            let oLi = document.createElement("li")
            oLi.innerHTML = curIndex + i;
            fragment.appendChild(oLi); //这时是看不出来的,因为是存在内存里,并不是真正的DOM
        }
        oContainer.appendChild(fragment);//这时是可以看出来的
        insert(curTotal - once,curIndex + once)
    });
}
insert(total,index) 

总结:根据创建li元素,频繁的触发了重排、重绘,所以使用createDocumentFragment方法来实现避免从而提高性能

从最基础到最优解方案,一步一步从而实现高性能渲染数据,达到目的。

近期热门文章

专栏推荐

推荐一下自己的专栏,欢迎大家收藏关注😊~