简体   繁体   中英

Jquery - Append vs AppendTo

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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