简体   繁体   English

Jquery - Append 与 AppendTo

[英]Jquery - Append vs AppendTo

Can somebody explain me why regular Append into a loop works better than AppendTo?有人能解释一下为什么常规 Append into a loop 比 AppendTo 效果更好吗?

//Using Regular Append
var ul = $("<ul></ul>");
$("#myDiv").empty().append(ul)

$.each(movies, function (count, item) {
    var id = 'li_' + count;
    ul.append('<li id=' + id + '>' + item + '</li>');

    $('#' + id).click(function () { });
});

//Using AppendTo
var div = $("#myDiv").empty(),
    ul = $("<ul></ul>").appendTo(div);

$.each(movies, function (count, item) {
    $('<li>' + item + '</li>').click(function () { }).appendTo(ul);
});

Result http://jsperf.com/sdp-jquery-append/3结果http://jsperf.com/sdp-jquery-append/3

append vs appendTo performance (jQuery 1.9.1) append vs appendTo 性能(jQuery 1.9.1)

From what can be seen in jQuery code, one of the reasons appendTo has better performance, is because appendTo implementation is slightly more complicated than regular append.从jQuery代码中可以看出,appendTo性能更好的原因之一,是因为appendTo的实现比普通的append稍微复杂一些。

While append depends roughly on native appendChild function, appendTo is a jQuery addition which needed to be handled by code (there's additional loop inside appendTo which operates on elements and actually calls .append again).虽然 append 大致依赖于原生的 appendChild 函数,但 appendTo 是一个需要由代码处理的 jQuery 添加(在 appendTo 内部有一个额外的循环,它对元素进行操作并实际再次调用 .append)。 While the performance hit isn't big (if you just compare simplest usage, like in this example: http://jsperf.com/sdp-jquery-append/5 ), it certainly is something to keep in mind.虽然性能影响不大(如果你只是比较最简单的用法,比如在这个例子中: http : //jsperf.com/sdp-jquery-append/5 ),它当然是需要记住的。

As to example labeled "Better" in linked jsperf:至于在链接的 jsperf 中标记为“更好”的示例:

It performs better, because in fastest version (in jsperf you linked to) you just collect html to be appended, instead of actually appending it on every iteration.它的性能更好,因为在最快的版本中(在您链接到的 jsperf 中),您只需收集要附加的 html,而不是在每次迭代时实际附加它。

It saves browser resources, since it don't have to reflow and repaint the content on every iteration.它节省了浏览器资源,因为它不必在每次迭代时重排和重新绘制内容。

append(content) appends content to the inside of every matched element. append(content)将内容附加到每个匹配元素的内部。

appendTo(selector) appends all of the matched elements to another specified set of elements. appendTo(selector)将所有匹配的元素附加到另一个指定的元素集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM