Optimization Monday — Part III: append elements after doing all modifications
Optimization Monday September 3rd, 2007Todays hint is: append newly created HTML element objecs to the document object first when all modifications to them are done. This can lead to great performance boots, because style or behavior changes (during the creation process) do not have to be applied by the browser.
So to improve this code snippet
var blockElement = document.createElement('div'); var paragraphElement = document.createElement('p'); var boldElement = document.createElement('b'); document.body.appendChild(blockElement); blockElement.appendChild(paragraphElement); blockElement.firstChild.appendChild(boldElement); blockElement.firstChild.firstChild.innerHTML = 'test paragraph'; blockElement.className = 'myClass';
apply the newly created element at the end.
var blockElement = document.createElement('div'); var paragraphElement = document.createElement('p'); var boldElement = document.createElement('b'); blockElement.appendChild(paragraphElement); blockElement.firstChild.appendChild(boldElement); blockElement.firstChild.firstChild.innerHTML = 'test paragraph'; blockElement.className = 'myClass'; document.body.appendChild(blockElement);
If the style settings described in myClass are applied to blockElement's child nodes, they have to be rendered again — even if they were just added to the document.