August 29

DOM Fragments & Adding to the DOM

Reflow is one of the most expensive browser processes, it can slow down your browser or in some extrem cases, especially on mobile crash it. Reflow is the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. Reflow happens, when you add or remove elements of the DOM.

Try to minimize the amount of DOM operations!

JavaScripts Document Fragments are a perfect solution to reduce that process, you will be able to add all your new elements with one DOM manipulation (assuming they are not spread across the document)


// adding 1000 divs to do the DOM with one DOM manipulation

var fragment = document.createDocumentFragment(), i, div;

for (i=0; i < 1000; i++) {
    div = document.createElement("div");
    div.innerHTML = "lorem ipsum dolor";

My DOM fragment module:

I created a module for a project to help me add content to the DOM, it uses DOM fragments and works as a templating module.

// how to use it

var tab = new MyModules.CreateFragment();
var tabContent = new MyModules.CreateFragment();
var h5Content = LLaneza.CreateFragment();

    .addLink("#", "that's a link<br/>")
    .addTag("span", "that's a span", "span--block");

    .addTag("h3", "some title")
    .addTag("p", "some text", "some-class")
    .appendFragment("h5", h5Content)
    .addList("ul", ["first item", "second item"], "classname")

if (true) { 

    tabContent.addLink("xxxxx.html", "view detail", "btn"); 

    .addLink("#", "<i class='icon'></i>", "js-close", "click", closeTab)
    .appendFragment("div", tabContent, "inner") // with wrapper tag
    .appendFragment(null, tabContent) // without wrapper tag
    .addToDom("project-tab") // id of the dom element
    .show(); // can be used to add loading transition

Download the DOM fragment module