Skip to main content
Ben Nadel at RIA Unleashed (Nov. 2009) with: Dee Sadler
Ben Nadel at RIA Unleashed (Nov. 2009) with: Dee Sadler ( @DeeSadler )

jQuery Appends Multiple Elements Using Efficient Document Fragments

Published in Comments (6)

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>
	<title>Testing jQuery's Use Of Document Fragments</title>

		Testing jQuery's Use Of Document Fragments

	<p class="nodes">
		<!-- To be populated dynamically. -->

	<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 );



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.
			"Is Fragment:",
			(document.createDocumentFragment().nodeType == elem.nodeType)

		// Check the length of the element.

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

Want to use code from this post? Check out the license.

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 ?



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



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



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


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

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel