Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top