Update 2
Here's a hackish sort of solution, that may be worth a little browser detection. It brings the performance in my testing down to less than 1/10 of what it was.
You can display='none'
追加之前的容器,然后再次显示。您可能会得到一点闪光,但这可能比长时间延迟要好。
window.onload = function(){
var content = String.fromCharCode(Math.floor(Math.random() * 1000));
// cache it in case it is already set
var disp = document.body.style.display;
document.body.style.display = 'none';
var now = new Date().getTime();
for(var i = 0; i < 10000; i++){
document.body.appendChild(document.createElement("div"))
.appendChild(document.createTextNode( content ));
}
setTimeout(function(){
console.log(new Date().getTime() - now);
document.body.style.display = disp || ''; // restore it
},0);
};
这是我所期望的性能提升documentFragment
.
Update
运行后修改版 http://jsfiddle.net/rZzYk/3/ of @Esailija的 https://stackoverflow.com/users/995876/esailijajsFiddle 测试包括文档片段,它似乎在 Chrome(或 Opera)中没有任何区别,因此看起来 Chrome 只是速度较慢。
“有什么办法可以加快速度吗?”
我猜如果你使用的话你会获得更好的性能documentFragment
,然后使用一个附加到 DOM.appendChild
.
window.onload = function(){
var now = new Date().getTime();
// create a documentFragment
var frag = document.createDocumentFragment();
for(var i = 0; i < 10000; i++){
frag.appendChild(Div()); // append to the documentFragment
}
// append the documentFragment (which is emptied)
document.body.appendChild(frag);
setTimeout(function(){
console.log(new Date().getTime() - now);
},0);
function Div(){
var This = document.createElement("div");
return This;
}
}