Updating an element style using javascript is pretty easy: document.getElementById(id).style.property = new style. But what if we have hundreds/thousands/.. elements to be updated? Calling the property setter above will force page re-rendering every time, so it would take considerable time. That's where bulk update is really helpful. Instead of applying styles after every change we can compose the css sheet with all the styles collected together and appy it at once.
Just compare
for (let i = 1; i < 10000; i++) { let li = document.getElementById(`li_${i}`); li.style.background = getRandomColor(); li.style.marginTop = "3px"; }
With that
//If the <style> element with the ID 'allStyles' already exists remove it let existingStyleElement = document.getElementById('allStyles'); if (existingStyleElement) { document.getElementsByTagName("head")[0].removeChild(existingStyleElement); } //Compose the string of all styles to be applied let styles = ''; for (let i = 1; i < 10000; i++) { styles += ` #li_${i}{background: ${getRandomColor()}; margin-top: 3px;}`; } //Create the <style> element with the ID 'allStyles' let styleElement = document.createElement('style'); styleElement.type = 'text/css'; styleElement.id = 'allStyles'; //Add collected styles to the <style> element styleElement.appendChild(document.createTextNode(styles)); //Insert the <style> element into the <head> document.getElementsByTagName("head")[0].appendChild(styleElement);
When we append the style element to the head, whole the stylesheet will be applied.
Of course, when there are just few style changes it is definetely no reason to utilize that approach, much simplier to use the first one. Applying style sheet gave me 3x time benefit in case when I had 10000+ elements on the page.
No comments:
Post a Comment