Render speed: adding one DOM item at a time or adding set of items at once

為{幸葍}努か 提交于 2020-01-05 06:03:14

问题


Currently when I receive results from search I loop through results and append it to a list (I guess this causes browser to re-render page every time item is added - is there a way to confirm this?).

$.each(results, function(key, val){
    $(".results").append("<div>"+ val +"</div>");
});

In this part of the second browser lags a bit (there are animations and stuff...). Would be more efficient to create separate div.results and add items in javascript then replace it in dom? What would be the most efficient way to do this? And how are this things usually done?


回答1:


What I would do is use document.createDocumentFragment() and do all possible operations there, and touch the real DOM once. (Beside in a loop might be a good idea to cache the selector once):

var frag = document.createDocumentFragment();
$.each(results, function(key, val){
    var a = document.createElement("div");
    a.innerHTML = val;
    frag.appendChild(a);
});
$(".results").append(frag);



回答2:


You're re-querying the DOM every iteration of the loop. There's no reason for this if you don't think that the number of .results elements is going to change while you're looping.

And if you're concerned about performance, you can reduce your use of jQuery.

var frag = document.createDocumentFragment();
$.each(results, function(key, val){
    frag.appendChild(document.createElement("div"))
        .appendChild(document.createTextNode(val))
});

// Since you're using a class, I assume there's more than one `.results` element
$(".results").each(function(i, el) {
     el.appendChild(frag.cloneNode(true));
});


来源:https://stackoverflow.com/questions/17632285/render-speed-adding-one-dom-item-at-a-time-or-adding-set-of-items-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!