Vue中fragment.js使用详解
createDocumentFragment如果想一次在一个节点上插入多个元素怎么办,比如一次插入10000个节点?最简单粗暴的方式是:varparent=document.getElementById(`'parent'`);for`(`vari=0;i<10000;i++){varchild=document.createElement(`'div'`);vartext=document.createTextNode(`''+i);`child.appendChild(text);parent.appendChild(child);}但是,由于众所周知的原因,对DOM的重复操作会导致页面重绘和reflow,效率很低,而且页面可能会卡住,这段代码基本没用。如果分段进行DOM操作,可以避免页面卡住。js忍者秘籍中提到可以使用setTimeout来改善:vari=0,max=10000;setTimeout(`functionaddNodes(){`for`(`varstep=i+500;ixxx'`;`console.log(div);实际输出是(在chrome下):<`div>xxx
didn'tgetwhatyouwant:<`div>
xxx | 这样的结果是可以理解的,毕竟一个th放在div里面,不管怎么看,直接去掉外围标签,把内容丢到div里面还是挺聪明的。但是我受不了,有时候只想得到一个th节点。其实好办,全部写就可以了:varnode=document.createElement(`'div'`);node.innerHTML='
'`;`//去掉外层就是想要的thvardepth=3;while`(depth--){`node=node.lastChild;}console.log(node.firstChild);可见结果正是你想要的。fragment.js//一些需要单独处理的特殊节点varmap={legend:[1,'
'],tr:[2,'
'],col:[2,'
'],_default:[0,'','']};map.td=map.th=[3,'
'];map.option=map.optgroup=[1,'
',''];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,'']map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'',''];varTAG_RE=/<([\w:]+)/;模块。exports=function(templateString){varfrag=document.createDocumentFragment(),m=TAG_RE.exec(templateString);//简单字符串if(!m){frag.appendChild(document.createTextNode(templateString);returnfrag;}vartag=m[1],wrap=map[tag]||map._default,depth=wrap[0],prefix=wrap[1],suffix=wrap[2],node=document.createElement('div');//拼接节点字符串node.innerHTML=prefix+templateString.trim()+suffix;//去掉外层包裹,只留下字符串转换节点while(depth--)node=node.lastChild;//只有一个节点if(node.firstChild===node.lastChild){frag.appendChild(node.firstChild);returnfrag;}//多个节点,加入fraginsequencevarchild;while(child=node.firstChild){frag.appendChild(child);}returnfrag;}参考https://www.jb51.net/article/...