KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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');
Tags (comma-separated)
Save Edits
Cancel