原文地址: http://www.cnitblog.com/asfman/articles/32614.html
一旦把節點添加到document.body(或其後的節點)中,頁面就會立即反映出這個變化。對於少量的更新,這是很好的。然而,當要向document.body添加大量數據時,如果逐個添加這些節點,這個過程有可能會十分緩慢。爲解決這個問題,可以創建一個文檔碎片,把所有的新節點附加其上,然後把文檔碎片的內容一次性添加到document中。
假設你想創建十個新段落。你可能這樣寫:
var arrText=["1","2","3","4","5","6","7","8","9","10"];
for(var i=0;i<arrText.length;i++)
{
var op=document.createElement("P");
var oText=document.createTextNode(arrText[i]);
op.appendChild(oText);
document.body.appendChild(op);
}
這段代碼運行良好,但問題是它調用了十次document.body.appendChild(),每次要產生一次頁面刷新。這時,文檔碎片會更高效:
var arrText=["1","2","3","4","5","6","7","8","9","10"];
var oFrag=document.createDocumentFragment();
for(var i=0;i<arrText.length;i++)
{
var op=document.createElement("P");
var oText=document.createTextNode(arrText[i]);
op.appendChild(oText);
oFrag.appendChild(op);
}
document.body.appendChild(oFrag);
這段代碼中,document.body.appendChild()僅調用了一次,這意味首隻需要進行一次屏幕的刷新。