Reputation: 347
I want adding elements to DOM while avoid page reflowing.
My questions:
var Span = document.createElement('span');
document.body.appendChild(Span);
// Span doesn't contain any child node
// and isn't setted or inherited any style
// so Span has width = height = 0
Will adding Span to DOM cause page reflowing?
// After adding Span to DOM,
// I need to add style and text to Span.
// In order to avoid page reflowing, I set style 'display:none' to Span.
Span.style.cssText = 'display:none;other:value';
Span.textContent = 'some text';
Can I use style.cssText
property to set display:none
and other css properties and avoiding page reflowing?
Or do I have to set style.display = none
to avoid page reflowing first then use cssText
to set other properties later?
Waiting for your advice and thanks for reading!
Upvotes: 0
Views: 797
Reputation: 4081
Adding or changing most things in the DOM will cause reflows. As suggested by commenters above, the best approach is to build the subtree of elements outside the DOM and then append it all at once:
var newDiv = document.createElement('div');
newDiv.style.someStyleProperty = 'someStyleValue'; // repeat as needed
newDiv.innerHTML = 'some tags and text';
document.body.appendChild(newDiv);
This will cause a single reflow, at the end when you call appendChild
.
Upvotes: 1