Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with:

jQuery Appends Multiple Elements Using Efficient Document Fragments

By Ben Nadel on

Earlier today, in my blog post on using jQuery's $.map() method, I talked about creating a buffer of detached DOM (Document Object Model) nodes. The value-add behind that post was the fact that the DOM nodes remained detached as long as possible; this allows them to be created and configured without incurring the cost of DOM rendering and repainting. As a follow-up to that concept, I wanted to do a little debugging in the jQuery library to see how the DOM node buffer was actually being appended to the rendered document.

The jQuery library is dense! While I have become pretty good at finding things within it, I am still quite an amateur when it comes to actually following the code flow and logic. Based on some experiments that John Resig performed a few years ago, it makes sense that the library would make use of Document Fragments to improve performance. But, I couldn't tell you from looking at the code whether or not this is true.

So, I decided to put some logging in the library to help clarify the situation. In the following demo, I'm simply creating an array of detached DOM nodes and then inserting them into the rendered document.

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <title>Testing jQuery's Use Of Document Fragments</title>
  • </head>
  • <body>
  •  
  • <h1>
  • Testing jQuery's Use Of Document Fragments
  • </h1>
  •  
  • <p class="nodes">
  • <!-- To be populated dynamically. -->
  • </p>
  •  
  •  
  • <script type="text/javascript" src="./jquery-1.7temp.js"></script>
  • <script type="text/javascript">
  •  
  •  
  • // Get a reference to the parent element.
  • var nodes = $( "p.nodes" );
  •  
  • // Create a buffer of detached DOM nodes.
  • var nodeBuffer = [
  • document.createTextNode( "Hello " ),
  • document.createTextNode( "my " ),
  • document.createTextNode( "love." )
  • ];
  •  
  • // Append the DOM buffer to the parent.
  • nodes.append( nodeBuffer );
  •  
  •  
  • </script>
  •  
  • </body>
  • </html>

As you can see, our demo creates an array with three detached Text Nodes. This array is then passed to the append() method which, subsequently, inserts it into the rendered DOM tree.

But, how does the insertion take place? To figure this out, I opened up the jQuery library, found the append() method definition, and added some debug code:

  • append: function() {
  • return this.domManip(arguments, true, function( elem ) {
  •  
  •  
  • // -- BEGIN: Debug. ---------- //
  • // --------------------------- //
  •  
  • // Check the type of target node that is be appending
  • // to the current node.
  • console.log( "Append:", elem.nodeType );
  •  
  • // Check to see if this is a fragment.
  • console.log(
  • "Is Fragment:",
  • (document.createDocumentFragment().nodeType == elem.nodeType)
  • );
  •  
  • // Check the length of the element.
  • console.log(
  • "Length:",
  • elem.childNodes.length
  • );
  •  
  • // Dump the fragments.
  • console.log( elem.childNodes[ 0 ] );
  • console.log( elem.childNodes[ 1 ] );
  • console.log( elem.childNodes[ 2 ] );
  •  
  • // --------------------------- //
  • // -- END: Debug. ------------ //
  •  
  •  
  • if ( this.nodeType === 1 ) {
  • this.appendChild( elem );
  • }
  • });
  • }

As you can see, this debug code is examining the type and contents of the element being inserted into the parent DOM node. When we run the above demo with the embedded debug code, we get the following console output:

Append: 11
Is Fragment: true
Length: 3
<TextNode textContent="Hello ">
<TextNode textContent="my ">
<TextNode textContent="love.">

As you can see, the element being inserted is a Document Fragment (nodeType 11). This Document Fragment is a lightweight node implementation that contains the three Text Nodes we created in our demo. However, since we passed in an array of nodes, it is safe to say that jQuery created and populated this fragment on our behalf (for performance reasons).

Cool stuff! The take-away here is that if we create detached node buffers, jQuery will optimize the insertion using fragments. In other words, the benefit of delaying DOM rendering and repainting is maintained through the whole process.




Reader Comments

Normally when I have to generate something simple like the list in your example I use $.map to create a array of strings and then follow up by $(...).append(array_of_strings.join()).

Is the only reason for creating document fragments that you can manipulate them with jQuery? Or are there also other concerns ?

Reply to this Comment

@Morten,

Yeah, the only reason I would do it this way (as opposed to an Array of string fragments) is if I wanted to use jQuery collections to be able to modify the elements before they were inserted into the document. If all I needed to do was template-string replacements (which this demo could have ultimately done), then I could have just used .replace() to "configure" the elements in a string-only buffer.

So yeah, this approach is for jQuery-based manipulation (in my mind).

Reply to this Comment

@Ben,

Yeah, I thought as much. Do you know of any benchmarks on using 'jQuery', '.replace()', 'string concatenation' -based manipulation?

Reply to this Comment

@Morten,

I don't really know of any comparison. Plus, a comparison might not be all that great when it comes to templating systems. I say this because I believe that most templating systems actually compile their templates down to inline JavaScript code rather than .replace() methods. So, there is a large up-front compile cost; but then creating template instances I believe is super fast.

Of course, speed here is all relative; I am sure that every approach is fast when it comes to what the browser can handle, until you get into massive amounts of data or something???

Reply to this Comment

@Ben,
Yeah, your probably right - what ever solution you chose caching should be involved.
I fail to see an HTML/Javascript app having a template usage that it would seriously effect your experience?

I guess things like this is more of a problem when done server-side than client-side...

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.