Jquery - Append vs AppendTo

2019-06-11 13:28发布

Can somebody explain me why regular Append into a loop works better than 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

2条回答
在下西门庆
2楼-- · 2019-06-11 13:30

append(content) appends content to the inside of every matched element.

appendTo(selector) appends all of the matched elements to another specified set of elements.

查看更多
冷血范
3楼-- · 2019-06-11 13:35

append vs appendTo performance (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.

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). 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.

As to example labeled "Better" in linked 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.

It saves browser resources, since it don't have to reflow and repaint the content on every iteration.

查看更多
登录 后发表回答