平时项目中会有一些流程,或者是评论相关的东西,这些一般只会是在页面初次加载一部分,剩余部分搞一个更多的标签,当点击更多的时候,ajax请求把所有数据加载完(当然这里也有分页的实现方法,本篇不作讨论), ajax加载的数据一般会运用到appendChild,insertBefore方法来附加在原来标签前后,相信大家对循环附加一定很熟练了,这里我要写的是另一种在性能方面比较赞的方法--运用文档片段,在低版本的IE下,缺少优化机制,循环附加造成的回流和渲染,会让浏览器hold不住(几何改变会造成浏览器重排)
看看一般appendChild做法,当然你可以直接innerHtml或者jquery的Html到容器上,这里是考虑原HTML可能包含事件,才把Html字符串转换为节点。
var ele=document.creatElement("div"); ele.innerHtml=html;//ajax获取到的 var divs=ele.childNodes;//所以子节点 for(var i=0,length=divs.length;i<length;i++) { container.appendChild(divs[i].cloneNode(true));//克隆到需要附加的容器 }
优化:
//接上例子
var fragment=document.createDocumentFragment(); for(var i=0;length=divs.length;i++){
fragment.apendChild(divs[i].cloneNode(true)); }
//最后一次性附加到容器
container.appendChild(fragment);
扩展原型:
//IE9+
//IE678隐藏了对HTMLElement的访问
//请用var appendHtmlOp=function(el,html){
// el.appendChild(frament);//这里不能用this,this指向了window;
//}
HTMLElement.prototype.appendHtmlOp=function(html){
var div=document.createElement("div"),nodes=null,
fragment=document.createDocumentFragment(); div.innerHTML=html;
nodes=div.childNodes;
for(var i=0,length=nodes.length;i++){
fragment.appendChild(nodes[i].cloneNode(true));
}
this.appendChild(fragment);
//释放
nodes=null;
fragment=null; }
同理也是可以直接修改insertBefore的;把前面的最后的appendChild改为insertBefore;
当然可以传个标识参数来区分;
var appendHtmlOp=function(el,html,where){
var div=document.createElement("div"),fragment=document.createDocumentFragment();nodes=null; where=where||"bottom";
div.innertHTML=html;
nodes=div.childNodes;
for(var i=0,length=nodes.length;i<length;i++){
fragement.appendChild(nodes[i].cloneNode(true));
}
where!=="before"?el.appendChild(fragment):el.insertBefore(fragment,el.firstChild);
}
这就是文档片段优化法,来减少appendChild多次直接附加在HTML后,使其呈现几何数值增加;