Does jQuery use to create a document fragment inside each loop?

So, I read that jQuery uses document fragments inside to make rendering faster. But I am wondering if anyone knows if jQuery can use createDocumentFragment in this situation when I add img elements to the DOM using each loop?

var displayArray = []; // Lots of img elements $.each(displayArray, function() { $('#imgSection').append(this); }); 

Or will I need to use this code to reduce the number of browser clicks?

 var displayArray = []; // Lots of img elements var imgHolder = $('<div/>'); $.each(displayArray, function() { imgHolder.append(this); }); $('#imgSection').append(imgHolder); 

In addition, displayArray is populated with other code, not shown here, that creates img elements based on paths in the JSON file.

Thanks for any advice.

+6
source share
3 answers

Why all the loops for adding items?

 $('#imgSection').append("<div>" + displayArray .join("") + "</div>"); 

Strike>

Good, so these are the elements.

The fastest way is to use append with the array itself.

 $("#out").append(elems); 

another option using one div to add

 var div = $("<div/>").append(elems); $("#out").append(div); 

BUT adding a large number of images at once will be bad if they are not preloaded. This will be a bunch of http requests standing in line.

jsPerf test cases

+7
source
  • No, if you use $.each() , then jQuery will not use DocumentFragment - jQuery does not know what you are going to do inside the loop, and each iteration is independent.

  • The point of a document fragment is that you do not need to wrap all your new elements in a shell element, as you did in the second example - a fragment can contain several elements, all of which will be inserted at the desired point. If your elements need a common parent, then you do not need document fragments.

  • jQuery will obviously use a document fragment if you pass an array of elements directly to .append() instead of iterating over them yourself.

+5
source

If you really care about recalculations (and notice that the display will be slow), you can hide and show the image holding element:

 var displayArray = […]; // Lots of img elements var holder = $('#imgSection').hide(); for (var i=0; i<displayArray.length; i++) holder.append(displayArray[i]); holder.show(); 
0
source

All Articles