我是 reading about document fragments和 DOM 重排,想知道 document.createDocumentFragment
与 document.createElement
有何不同,因为在我将它们附加到 DOM 元素之前,它们似乎都不存在于 DOM 中。
我做了一个测试(如下),所有这些都花费了完全相同的时间(大约 95 毫秒)。猜测这可能是由于没有样式应用于任何元素,所以可能没有重排。
无论如何,根据下面的示例,为什么我在插入 DOM 时应该使用 createDocumentFragment
而不是 createElement
,两者之间有什么区别。
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 中插入文档片段的位置,而文档片段本身并未插入。片段本身继续存在,但现在没有 child 。
这允许您同时将多个节点插入到 DOM 中:
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
关于javascript - 我应该使用 document.createDocumentFragment 还是 document.createElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3397161/