如果对客户端动态交互要求比较高,在DOM里需要频繁动态增加元素,那么可能会遇到性能问题,那么就有可能用到DocumentFragment了,具体看看下面的例子,性能差别还是挺大的。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function slowAdd() {
for (var i = 0; i < 10000; i++) {
var op = document.createElement("span");
var oText = document.createTextNode(i);
op.appendChild(oText);
document.body.appendChild(op);
}
}
function fastAdd(){
var oFragmeng = document.createDocumentFragment(); //创建文档碎片
for (var i = 0; i < 10000; i++) {
var op = document.createElement("span");
var oText = document.createTextNode(i);
op.appendChild(oText);
oFragmeng.appendChild(op);
}
document.body.appendChild(oFragmeng); //最后一次性添加到document中
}
</script>
</head>
<body>
<p>
<input id="Button1" type="button" value="button" onclick = "slowAdd()"/></p>
<p>
<input id="Button2" type="button" value="button" onclick = "fastAdd()"/></p>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function slowAdd() {
for (var i = 0; i < 10000; i++) {
var op = document.createElement("span");
var oText = document.createTextNode(i);
op.appendChild(oText);
document.body.appendChild(op);
}
}
function fastAdd(){
var oFragmeng = document.createDocumentFragment(); //创建文档碎片
for (var i = 0; i < 10000; i++) {
var op = document.createElement("span");
var oText = document.createTextNode(i);
op.appendChild(oText);
oFragmeng.appendChild(op);
}
document.body.appendChild(oFragmeng); //最后一次性添加到document中
}
</script>
</head>
<body>
<p>
<input id="Button1" type="button" value="button" onclick = "slowAdd()"/></p>
<p>
<input id="Button2" type="button" value="button" onclick = "fastAdd()"/></p>
</body>
</html>
参考资源:http://www.cssrain.cn/article.asp?id=1421
本文转自Justin博客园博客,原文链接:http://www.cnblogs.com/justinw/archive/2009/12/02/1615382.html,如需转载请自行联系原作者