更新2
這裏有一個hackish的某種解決方案,這可能是值得一小的瀏覽器檢測。它將我測試中的性能降低到它不到的水平。
你可以在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
預期的業績增長。
更新
運行modified version的@Esailija's的jsfiddle測試包括的DocumentFragment後,它似乎並沒有把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;
}
}
'setTimeout'似乎有可能甩開你的時間。 – Domenic 2012-01-18 16:13:12
您可以一個接一個地插入div。 – 2012-01-18 16:14:55
@Domenic你需要setTimeout這種基準,以便在你獲得時間之前,瀏覽器確實能夠正常工作 – Esailija 2012-01-18 16:15:21