I was reading about document fragments and the DOM, and wondered how document.createDocumentFragment is different from document.createElement , because it looks like none of them exist in the DOM until I add them to the DOM element.
I did a test (below), and they all took exactly the same time (about 95 ms). This is probably possible due to the fact that the style does not apply to any of the elements, so there may be no possibility of melting.
In any case, based on the example below, why should I use createDocumentFragment instead of createElement when pasting into the DOM and what is the difference 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');
javascript dom
screenm0nkey Aug 03 '10 at 13:53 2010-08-03 13:53
source share