Javascript Document Fragment (Very Simple Example)

Welcome to a quick tutorial on how to use the Javascript document fragment. Congratulations code ninja, you have found one of the underrated gems in Javascript and HTML.

The document fragment is a lightweight container for creating HTML elements, an alternative to directly inserting elements into the DOM. A quick example:

  • var fragment = new DocumentFragment();
  • let row = document.createElement("div");
  • row.innerHTML = "CONTENT";
  • fragment.appendChild(row);
  • document.getElementById("ID").appendChild(fragment);

So… Isn’t it slower to append to a fragment first, then append the fragment to the document? Why this “dumb and roundabout” way of adding HTML elements? Let us walk through a few examples in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Document Fragment Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

DOCUMENT FRAGMENT

All right, let us now walk through some examples of using the document fragment.

 

1) CREATING DOCUMENT FRAGMENTS

1A) THE HTML

1-create-fragment.html
<!-- (A) LIST TO APPEND TO -->
<ul id="thelist">
  <li>Apple - A juicy red fruit, sometimes green.</li>
</ul>

For this example, we will be appending more rows to this simple list.

 

1B) THE JAVASCRIPT

1-document-fragment.html
// (B1) DATA TO ADD
var data = {
  Banana : "Long yellow fruit. Priced at $120,000 with a duct tape.",
  Cherry : "Small red berry thing.",
  Dragonfruit : "Not a dragon but a fruit.",
  Elderberry : "Wise old berry, +5 intelligence."
};
 
// (B2) CREATE DOCUMENT FRAGMENT
// CAN BE CREATED WITH NEW DOCUMENTFRAGMENT() OR DOCUMENT.CREATEDOCUMENTFRAGMENT()
var frag = new DocumentFragment();
// var frag = document.createDocumentFragment();
 
// (B3) APPEND DATA TO FRAGMENT
for (let fruit in data) {
  let row = document.createElement("li");
  row.innerHTML = `${fruit} - ${data[fruit]}`;
  frag.appendChild(row);
}

// (B4) APPEND FRAGMENT TO TABLE
document.getElementById("thelist").appendChild(frag);

As in the introduction above:

  • (B2) We create a new DocumentFragment() or document.createDocumentFragment() first.
  • (B3) Instead of directly appending new HTML elements into the document, we append to the fragment instead.
  • (B4) Append the fragment to the page.

 

 

2) DOCUMENT FRAGMENT VS DIRECT INSERTION

Some of you smart code ninjas should be confused now. Why are we doing this “dumb roundabout thing” of creating a document fragment, isn’t direct insertion better and faster? Well, let’s find out with a small experiment.

 

2A) DIRECT INSERTION

2a-direct-insert.html
<!-- (A) TABLE TO APPEND TO -->
<table id="thetable"></table>
 
<!-- (B) JAVASCRIPT -->
<script>
// (B1) START TIMING
var start = new Date();

// (B2) GENERATE A LOT OF TABLE ROWS + CELLS
var thetable = document.getElementById("thetable");
for (let i=1; i<=1000; i++) {
  let row = document.createElement("tr"),
      cellA = document.createElement("td"),
      cellB = document.createElement("td"),
      cellC = document.createElement("td"),
      cellD = document.createElement("td");
  cellA.innerHTML = "Cell A" + i;
  cellB.innerHTML = "Cell B" + i;
  cellC.innerHTML = "Cell C" + i;
  cellD.innerHTML = "Cell D" + i;
  row.appendChild(cellA);
  row.appendChild(cellB);
  row.appendChild(cellC);
  row.appendChild(cellD);
  thetable.appendChild(row);
}

// (B3) ELAPSED TIME
var time = new Date() - start;
console.log("Elapsed: " + time);
</script>

In this test script, we are directly inserting 1000 rows of 4 cells into a table. On my PC, this took 18 ms. Not too bad for a massive table.

 

 

2B) FRAGMENT INSERTION

2b-fragment-insert.html
<!-- (A) TABLE TO APPEND TO -->
<table id="thetable"></table>

<!-- (B) JAVASCRIPT -->
<script>
// (B1) START TIMING
var start = new Date();

// (B2) GENERATE A LOT OF TABLE ROWS + CELLS
var frag = new DocumentFragment();
for (let i=1; i<=1000; i++) {
  let row = document.createElement("tr"),
      cellA = document.createElement("td"),
      cellB = document.createElement("td"),
      cellC = document.createElement("td"),
      cellD = document.createElement("td");
  cellA.innerHTML = "Cell A" + i;
  cellB.innerHTML = "Cell B" + i;
  cellC.innerHTML = "Cell C" + i;
  cellD.innerHTML = "Cell D" + i;
  row.appendChild(cellA);
  row.appendChild(cellB);
  row.appendChild(cellC);
  row.appendChild(cellD);
  frag.appendChild(row);
}
document.getElementById("thetable").appendChild(frag);

// (B3) ELAPSED TIME
var time = new Date() - start;
console.log("Elapsed: " + time);
</script>

The results speak for themselves, the so-called “dumb and roundabout” document fragment took 9 ms. That’s half of the direct insertion, nearly twice in a performance boost.

 

 

USEFUL BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Document Fragment (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.