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!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

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 [k,v] of Object.entries(data)) {
  let row = document.createElement("li");
  row.innerHTML = `${k} - ${v}`;
  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.

 

 

EXTRAS

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

 

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. Required fields are marked *