More efficient jquery

this piece of code works, but it makes the browser pretend a bit. Nothing serious. I am wondering if there will be a way to make this more efficient? Can I use caching or somehow fill in one selection and then just copy it to another 5. (There are 6 drop-down lists on the page with the mask class.)

Any help would be greatly appreciated!

$('.mask').each(function () { $(this).append($('<option/>').val("").text("")); for (var i = 1; i < 256; i++) { $(this).append($('<option/>').val(i).text(i)); } }); }); 
+8
javascript jquery
source share
2 answers

You can create nodes after cloning, for example:

 var temp = $('<select/>'); $('<option/>').val("").text("").appendTo(temp); for (var i = 1; i < 256; i++) { $('<option/>').val(i).text(i).appendTo(temp); } temp.children().clone().appendTo('.mask'); 

Instead of making many separate additions to the DOM (which is very expensive), it combines all the elements in the document fragment and then clones them, adding packages (one batch of your choice).

+12
source share

It is much faster (about 3-10 times as tested here ) to create HTML yourself in one line:

 var html = "<option value=''></option>"; for (var i = 1; i < 256; i++) { html += "<option value='" + i + "'>" + i + "</option>"; } $(".mask").append(html); 

See a performance test comparing the current settings in this thread: http://jsperf.com/appending-options-jquery

+6
source share

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


All Articles