Is there evidence to support the claim that following the advice provided here (as shown below) on removing DOM elements before altering them and then re-inserting them actually results in faster performance?
I'm looking for concrete figures to back up this assertion. While it's great that research has been conducted on this topic, I believe the article lacks specifics on how the 'problem' is defined and how the proposed solution improves speed (as indicated by the article title Speeding up JavaScript).
The article describes a pattern called Out-of-the-flow DOM Manipulation which involves creating multiple elements outside of the DOM using a DocumentFragment before inserting them into the DOM to trigger a single reflow.
The problem
Consider a function that updates the className attribute for all anchors within an element. The conventional approach would involve iterating through each anchor and updating their attributes individually, resulting in a reflow for each anchor.
function updateAllAnchors(element, anchorClass) {
var anchors = element.getElementsByTagName('a');
for (var i = 0, length = anchors.length; i < length; i ++) {
anchors[i].className = anchorClass;
}
}
The solution
To address this issue, the article suggests temporarily removing the element from the DOM, updating all anchors, and then reinserting the element back to its original position. A reusable function named removeToInsertLater is provided to facilitate this process.
/**
* Remove an element and provide a function that inserts it into its original position
* @param element {Element} The element to be temporarily removed
* @return {Function} A function that inserts the element into its original position
**/
function removeToInsertLater(element) {
var parentNode = element.parentNode;
var nextSibling = element.nextSibling;
parentNode.removeChild(element);
return function() {
if (nextSibling) {
parentNode.insertBefore(element, nextSibling);
} else {
parentNode.appendChild(element);
}
};
}
By utilizing this function, we can efficiently update anchors within an out-of-the-flow element, minimizing reflows during the removal and insertion stages.
function updateAllAnchors(element, anchorClass) {
var insertFunction = removeToInsertLater(element);
var anchors = element.getElementsByTagName('a');
for (var i = 0, length = anchors.length; i < length; i ++) {
anchors[i].className = anchorClass;
}
insertFunction();
}