Question

Using DocumentFramgment allows us to attach DOM elements to each other without causing a browser reflow (i.e. work with offline DOM trees). A lot of libraries like jQuery use document fragments to improve performance.

The document fragment can have a complicated structure. For example, let's say it represents something like:

<div>
   <span>
       <a href='asd'>asd</a>
   </span>
   <span>
       <a href='asd2'>asd2</a>
   </span>
   <div>
       <div>
          Hello World
       </div>
   </div>
</div>

or a document fragment that contains multiple children:

<h2>Title 1</h2>
<p>Lorem ipsum.</p>
<p>Lorem ipsum.</p>
<h2>Title 2</h2>
<p>Lorem ipsum.</p>
<p>Lorem ipsum.</p>

Often, when we finish building the the fragment, we attach it to the main DOM tree.

How many reflows happen when we do this? Does it depend on the number of direct children of the document fragment?

Update:

I got a response from Addy Osmani who is on the Chrome team at Google:

Just one DOM reflow. PS: we're moving more towards referring to reflow as layout as it's basically an event triggering layout/repaint in the page.

Was it helpful?

Solution

A single DOM reflow process occurs each time an action causing one is invoked. We can read in this article that:

This pattern lets us create multiple elements and insert them into the DOM triggering a single reflow. It uses something called a DocumentFragment. We create a DocumentFragment outside of the DOM (so it is out-of-the-flow). We then create and add multiple elements to this. Finally, we move all elements in the DocumentFragment to the DOM but trigger a single reflow.

There are various actions that can cause a DOM reflow, including appending a new element to the document. The purpose of using a DocumentFragment is to be able to append content to the DOM in a single operation causing a single reflow process.

According to this article, we can read that:

Sometimes reflowing a single element in the document may require reflowing its parent elements and also any elements which follow it.

However, all these reflow operations will occur in a single reflow process.

I created a fiddle to demonstrate this. Using chrome's timeline, we can clearly see that rendering occurs in a single block.

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top