I was reading about document fragments and DOM reflow and wondered how document.createDocumentFragment
differed from document.createElement
as it looks like neither of them exist in the DOM until I append them to a DOM element.
I did a test (below) and all of them took exactly the same amount of time (about 95ms). At a guess this could possibly be due to there being no style applied to any of the elements, so no reflow maybe.
Anyway, based on the example below, why should I use createDocumentFragment
instead of createElement
when inserting into the DOM and whats the differnce between the two.
var htmz = "<ul>"; for (var i = 0; i < 2001; i++) { htmz += '<li><a href="#">link ' + i + '</a></li>'; } htmz += '<ul>'; //createDocumentFragment console.time('first'); var div = document.createElement("div"); div.innerHTML = htmz; var fragment = document.createDocumentFragment(); while (div.firstChild) { fragment.appendChild(div.firstChild); } $('#first').append(fragment); console.timeEnd('first'); //createElement console.time('second'); var span = document.createElement("span"); span.innerHTML = htmz; $('#second').append(span); console.timeEnd('second'); //jQuery console.time('third'); $('#third').append(htmz); console.timeEnd('third');
In an HTML document, the document. createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
If you ever find yourself appending a series of elements to the DOM, you should always use a DocumentFragment to do just that. Why? Not only is using DocumentFragments to append about 2700 times faster than appending with innerHTML, but it also keeps the recalculation, painting and layout to a minimum.
The document. createElement() accepts an HTML tag name and returns a new Node with the Element type.
The DocumentFragment interface represents a minimal document object that has no parent. It is used as a lightweight version of Document that stores a segment of a document structure comprised of nodes just like a standard document.
The difference is that a document fragment effectively disappears when you add it to the DOM. What happens is that all the child nodes of the document fragment are inserted at the location in the DOM where you insert the document fragment and the document fragment itself is not inserted. The fragment itself continues to exist but now has no children.
This allows you to insert multiple nodes into the DOM at the same time:
var frag = document.createDocumentFragment(); var textNode = frag.appendChild(document.createTextNode("Some text")); var br = frag.appendChild(document.createElement("br")); var body = document.body; body.appendChild(frag); alert(body.lastChild.tagName); // "BR" alert(body.lastChild.previousSibling.data); // "Some text" alert(frag.hasChildNodes()); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With