createDocumentFragment 的优势

原文地址: 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()仅调用了一次,这意味首只需要进行一次屏幕的刷新。

猜你喜欢

转载自blog.csdn.net/terrychinaz/article/details/113206960