dom中的文档碎片(DocumentFragment)
对文档碎片的基本认识
var b = document.getElementsByTagName('body')[0],
tmp = document.createDocumentFragment(),
s = new Date().getTime(),
num = 2*10000,
count = document.querySelectorAll("*").length + num;
function getSpendTimes(count,times){
return new Promise(function(resolve, reject) {
var curs = document.querySelectorAll("*").length;
var s = 0;
if(curs === count){
s = new Date().getTime()-times;
}
if (resolve){
resolve(s);
} else {
reject(0);
}
});
}
function getRenderTimes(count,times,call){
var s = 0;
getSpendTimes(count,times).then(function(times){
s = times;
if(s===0){
getRenderTimes(count,times,call);
}else{
call(s);
}
});
}
for(var i=0;i<num;i++){
var li = document.createElement("li");
li.textContent = i;
tmp.appendChild(li);
}
b.appendChild(tmp);
getRenderTimes(count,s,function(times){
console.log(times);
});
3.dom常规添加方式:
for(var i=0;i<num;i++){
var li = document.createElement("li");
li.textContent = i;
b.appendChild(li);
}
getRenderTimes(count,s,function(times){
console.log(times);
});
PC的firefox (版本 48.0.2) 测试的结果:
文档碎片加载时间(测试了5次):166 148 141 147 142
dom常规添加方式:1425 1359 1392 1324 1350
PC的chrome(版本 55.0.2883.87) 测试的结果:
文档碎片加载时间:60 68 56 41 59
dom常规添加方式:37 45 47 46 48
chrome对于文档操作优化的很好了,移动设备待测试ing