jQuery Appends Multiple Elements Using Efficient Document Fragments

Posted November 1, 2011 at 2:26 PM by Ben Nadel

Tags: Javascript / DHTML

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

Nov 1, 2011 at 8:32 PM // reply »
13 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 ?


Nov 2, 2011 at 6:02 PM // reply »
11,238 Comments

@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).


Nov 3, 2011 at 7:23 AM // reply »
13 Comments

@Ben,

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


Nov 7, 2011 at 10:01 AM // reply »
11,238 Comments

@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???


Nov 7, 2011 at 10:30 AM // reply »
13 Comments

@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...


Nov 7, 2011 at 10:38 AM // reply »
11,238 Comments

@Morten,

I tend to agree with you. Most of this stuff is going to be pretty fast!


Post A Comment

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.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
May 14, 2013 at 6:57 PM
The UX Of Prototyping: Low-Fidelity Is The New High-Fidelity
@Phillip, I'm not sure I follow what you mean? Are you saying that you looked at the list of widgets provided by the jQuery UI and let that be your style guide? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools