有人告诉我,当向 DOM 中插入多个元素时,首先分离目标元素,插入元素,然后将其附加回 DOM 会更有效。我想知道为什么。
例如,
html
<div id="main">
<ul class="list"></ul>
</div>
jQuery
var arrayOfElements = [$("<li> .... </li>"), $("<li> .... </li>"), ... , $("<li> ... </li>")]
# Appraoch 1
$(".list").html(arrayOfElements);
# Approach 2
$(".list").detach().html(arrayOfElements).appendTo(".main");
为什么方法 2 更高效,其重要性有多大?
最佳答案
将一系列元素附加到 DOM 时,每个元素都会触发浏览器重排页面。将一个元素添加到已经准备好的页面,但不在 DOM 上,然后将其追加到 DOM 只会导致页面的一次回流。
来自:http://www-archive.mozilla.org/newlayout/doc/reflow.html
All reflows have a reason, which is maintained in the reflow state object (and may mutate, as described below). The reflow reason controls how a frame reacts during a reflow, and is one of the following:
文章接着列出了回流的原因,以下是其中一个原因:
Incremental, when something in the frame tree changes; for example, when more content is read from the network, or some script manipulates the DOM. An incremental reflow is targeted at a single frame in the frame hierarchy. During an incremental reflow, a frame can assume that none of the constraints computed
from above'' (for example, available width) have changed; instead, something
within'' the frame has changed, which may have bottom-up impact to the frame hierarchy.
至于性能改进,我将把它留给 John Resig。
Browser Normal (ms) Fragment (ms)
Firefox 3.0.1 90 47
Safari 3.1.2 156 44
Opera 9.51 208 95
IE 6 401 140
IE 7 230 61
IE 8b1 120 40
来源:http://ejohn.org/blog/dom-documentfragments/
不过你的例子有些缺陷。
var arrayOfElements = [$("<li>....</li>"), $("<li>....</li>"), $("<li>...</li>")];
应该写成:
var arrayOfElements = ["<li>....</li>", "<li>....</li>", "<li>....</li>"].join('');
其次
// Approach 1
$(".list").html(arrayOfElements);
在这两个示例之间,这个可能实际上更好。为什么?
因为:
// Approach 2
$(".list").detach().html(arrayOfElements).appendTo("#main");
最多可导致(并且可能会)2 次回流。曾经当<ul>
从 DOM 中删除,并在追加到 DOM 时一次。 Approach 1
可能会导致 2 次(或更多)回流,如 .html
必须删除当前的子项,然后附加第二组。决定因素是 .html
方法将每个元素按顺序附加或一次性作为一个 DOM 元素附加。但至少它更容易理解。最多它会从 DOM 中少删除一个元素,从而可能减少回流的影响。
但是这两种方法都优于以下方法:
var arrayOfElements = ["<li>....</li>", "<li>....</li>", "<li>....</li>"];
$('.list').children().remove();
for (var i = 0; i < arrayOfElements.length; i++) {
$(arrayOfElements[i]).appendTo('.list');
}
关于jquery - 为什么分离和附加比直接更改 html 更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26767804/