文档碎片的作用:可以提高DOM操作性能(理论上),实际上不一定提高性能,反而降低性能。
比如下面的两个页面进行比较:点击普通按钮和碎片按钮进行比较两个弹出的时间大小;时间越大说明性能越低;
文档碎片--普通页面:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
window.onload=function(){
var oBtn=document.getElementById('btn1');
var oUl=document.getElementById('ul1');
oBtn.onclick=function(){
var iStart=new Date().getTime();
var i=0;
for(i=0; i<10000;i++){
var oLi=document.createElement('li');////建个新的节点li
oUl.appendChild(oLi);//把每一次oLi追加到oUl中
}
alert(new Date().getTime()-iStart);//所需要的用的时间
}
}
</script>
</head>
<body>
<input id="btn1" type="button" value="普通" />
<ul id="ul1">
</ul>
</body>
</html>
文档碎片--碎片页面:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
window.onload=function(){
var oBtn=document.getElementById('btn1');
var oUl=document.getElementById('ul1');
oBtn.onclick=function(){
var iStart=new Date().getTime();
var oFrag=document.createDocumentFragment();//创建文档碎片
var i=0;
for(i=0; i<10000;i++){
var oLi=document.createElement('li');//建个新的节点li
oFrag.appendChild(oLi);
//把每一次内容附加到文档碎片
}
oUl.appendChild(oFrag);//一次性把文档碎片追加到oUl中
alert(new Date().getTime()-iStart);//所需要的用的时间
}
}
</script>
</head>
<body>
<input id="btn1" type="button" value="碎片" />
<ul id="ul1">
</ul>
</body>
</html>
注意:一般情况下我们是不会使用文档碎片的;