Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many Reflows does attaching a DocumentFragment Cause?

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.

like image 894
Benjamin Gruenbaum Avatar asked Mar 31 '13 18:03

Benjamin Gruenbaum


1 Answers

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

like image 86
plalx Avatar answered Sep 20 '22 23:09

plalx