DocumentFragment
DocumentFragment对象是Node接口的实现类。按照MDN上的说法,该对象是文档碎片,常常被用于插入文档节点。将DocumentFragment插入到文档时,只会将它的所有子节点插入到文档中。网上有很多文章说,使用该对象可以提升js的效率,下面是我的一些验证,如有错误,不吝指正。
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" >
<style type="text/css">
#insert{
width: 300px;
height: 60px;
}
</style>
</head>
<body>
<h1 id="df">
Fragment:
</h1>
<h1 id="ndf">
直接插入:
</h1>
<div id="insert">
<!--
select
-->
</div>
<button id="btn1">Fragment插入</button>
<button id="btn2">直接插入</button>
<script type="text/javascript">
(function(window){
var parent = document.getElementById('insert');
var text = document.createTextNode('');
var df = document.getElementById('df');
var ndf = document.getElementById('ndf');
var start,end;
document.getElementById('btn1').onclick = function(){
start = new Date();
t = text.cloneNode();
useFragment();
setTimeout(function(){
end = new Date();
t.nodeValue = (end-start)+' ';
df.appendChild(t);
},0);
return false;
};
document.getElementById('btn2').onclick = function(){
start = new Date();
t = text.cloneNode();
useDirect();
setTimeout(function(){
end = new Date();
t.nodeValue = (end-start)+' ';
ndf.appendChild(t);
},0);
return false;
};
function useFragment(){
var fragment = document.createDocumentFragment();
var select = document.createElement('select'),
option = document.createElement('option'),
copy,
i;
for(i=0;i<20000;i++){
copy = option.cloneNode();
copy.setAttribute('value',i);
copy.innerHTML = i;
fragment.appendChild(copy);
}
select.appendChild(fragment);
parent.appendChild(select);
select = option = fragment = null;
}
function useDirect(){
var select = document.createElement('select'),
option = document.createElement('option'),
copy,
i;
for(i=0;i<20000;i++){
copy = option.cloneNode();
copy.setAttribute('value',i);
copy.innerHTML = i;
select.appendChild(copy);
}
parent.appendChild(select);
select = option = null;
}
})(this);
</script>
</body>
</html>
运行结果如下图。chrome:
FireFox:
IE:
结论
- 在chrome和firefox下面,可以看出,使用DocumentFragment和直接插入并没有什么区别,互有上下,有时候DocumentFragment甚至会比直接输入耗时高,因此,使用DocumentFragment和直接插入节点对于现代浏览器来说,基本是没有区别。
- 而在ie下,使用了DocumentFragment耗时3s才得出结果,而直接插入节点因为等了几十秒的时间都还没有结果,因此可以判断出,使用DocumentFragment对ie插入节点是有性能提升的。
- 实践出真知,希望大家能多多动手,网上有好多东西有人云亦云的情况。