documentFragment和template

今天读vue源码,读到了fragment。抱着一直以来的好奇,打开了mdn文档,只能说“又学习到了”。

A DocumentFragment is a minimal document object that has no parent. It is used as a light-weight version of document to store well-formed or potentially non-well-formed fragments of XML.

documentFragment特性

documentFragement可以作为append类(Node.appendChild,Node.insertBefore)方法的参数,但是只有它的children被append,本身却不会。

与template的配合

template不会被渲染,但仍在dom结构树中,可以通过getElement类方法找到它。
HtmlTemplateElement.content是documentFragment

利用这一点可以甄别浏览器对template的支持

if ('content' in document.createElement('template') {
    console.log('HTML template element is supported');
} else {
    console.log('the HTML template element is not supported');
}

MDN中非常好的示例

  • 获取template元素
  • content中找到需要修改的text或value
  • 利用document.importNode或者content.cloneNode克隆得到实例
  • 将新实例append进某元素中

性能优化

john Resig大神发现了利用documentFragment优化append类操作的途径。

但是个人感觉documentFragment的设定就是为了这个,比如这篇文章中谈及documentFragment应有的使用姿势

stackflow中也有关于这个的讨论,有人专门对两者的差别做了测试,差别仍然很大。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容