做一个总结和学习跟大家分享,希望对大家也有所帮助,共同成长进步💪~
如果大家喜欢,可以点赞或留言哈💕~~~~,谢谢大家⭐️⭐️⭐️~~~
第一种暴力形式
<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方法来实现避免从而提高性能
从最基础到最优解方案,一步一步从而实现高性能渲染数据,达到目的。
近期热门文章
- 垃圾回收机制的理解
- 实现Echarts 3D立体中国地图实现、世界地图、以及互相切换功能
- lucky-canvas 抽奖
- 宏任务和微任务的理解
- Js数组去重的多种方法
- vue使用echarts 实现世界地图、中国地图、以及下钻地图绘制
- JavaScript 的几种循环方式
- Js 数据类型转换的几种方式
- 手写【横柱带斜三角】进度条实现
专栏推荐
推荐一下自己的专栏,欢迎大家收藏关注😊~