JQuery - Append vs AppendTo

Can someone explain to me why regular adding to the 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

0
source share
2 answers

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 the implementation of appendTo is a bit more complicated than regular additions.

While append depends roughly on the built-in appendChild function, appendTo is a jQuery add-on that needs to be handled by code (there is an extra loop inside appendTo that works with the elements and actually calls .append again). While the performance hit is small (if you are simply comparing the simplest use, for example, in this example: http://jsperf.com/sdp-jquery-append/5 ), this is certainly to keep in mind.

As in the example with the inscription "Better" in the associated jsperf:

It works better because in the fastest version (in jsperf that you are attached to) you just collect the html to add, rather than adding it at each iteration.

It saves browser resources, since there is no need to reschedule and redraw the content at each iteration.

0
source

append(content) appends content to the internal content of each matched element.

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

0
source

Source: https://habr.com/ru/post/1245526/


All Articles