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

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

问题描述

我正在阅读文档fragment 和 DOM 回流,并想知道 document.createDocumentFragmentdocument.createElement 有何不同,因为在我将它们附加到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.

我做了一个测试(如下),所有这些都花费了完全相同的时间(大约 95 毫秒).猜测这可能是由于没有应用于任何元素的样式,因此可能没有回流.

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.

无论如何,基于下面的示例,我为什么要在插入 DOM 时使用 createDocumentFragment 而不是 createElement 以及两者之间的区别.

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天全站免登陆