我应该使用document.createDocumentFragment还是document.createElement [英] Should I use document.createDocumentFragment or document.createElement

查看:353
本文介绍了我应该使用document.createDocumentFragment还是document.createElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是阅读文件碎片和DOM回流,并想知道如何 document.createDocumentFragment document.createElement 不同,因为它看起来不像它们存在于DOM中,直到我将其附加到DOM元素。

I was reading about document fragments and DOM reflow and wondered how document.createDocumentFragment differed from document.createElement as it looks like neither of them exist in the DOM until I append them to a DOM element.

我做了一个测试(下面),所有的都花费了相当的时间量在95ms)。在猜测这可能是由于没有风格应用于任何元素,所以没有回流可能。

I did a test (below) and all of them took exactly the same amount of time (about 95ms). At a guess this could possibly be due to there being no style applied to any of the elements, so no reflow maybe.

无论如何,基于以下示例,为什么要使用 createDocumentFragment 而不是 createElement 当插入到DOM中,两者之间有什么不同。

Anyway, based on the example below, why should I use createDocumentFragment instead of createElement when inserting into the DOM and whats the differnce between the two.

var htmz = "<ul>";
for (var i = 0; i < 2001; i++) {
    htmz += '<li><a href="#">link ' + i + '</a></li>';
}
htmz += '<ul>';

//createDocumentFragment
console.time('first');
var div = document.createElement("div");
div.innerHTML = htmz;
var fragment = document.createDocumentFragment();
while (div.firstChild) {
    fragment.appendChild(div.firstChild);
}
$('#first').append(fragment);
console.timeEnd('first');

//createElement
console.time('second');
var span = document.createElement("span");
span.innerHTML = htmz;
$('#second').append(span);
console.timeEnd('second');


//jQuery
console.time('third');
$('#third').append(htmz);
console.timeEnd('third');


推荐答案

区别在于,当您的文档片段有效地消失将其添加到DOM。发生什么事情是,文档片段的所有子节点都插入到您插入文档片段的DOM中的位置,而不会插入文档片段本身。该片段本身继续存在,但现在没有孩子。

The difference is that a document fragment effectively disappears when you add it to the DOM. What happens is that all the child nodes of the document fragment are inserted at the location in the DOM where you insert the document fragment and the document fragment itself is not inserted. The fragment itself continues to exist but now has no children.

这允许您同时在DOM中插入多个节点:

This allows you to insert multiple nodes into the DOM at the same time:

var frag = document.createDocumentFragment();
var textNode = frag.appendChild(document.createTextNode("Some text"));
var br = frag.appendChild(document.createElement("br"));
var body = document.body;
body.appendChild(frag);
alert(body.lastChild.tagName); // "BR"
alert(body.lastChild.previousSibling.data); // "Some text"
alert(frag.hasChildNodes()); // false

这篇关于我应该使用document.createDocumentFragment还是document.createElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆