Problem:
I have a list of text labels and I need to get a width of those labels when rendered inside the browser. So I’m creating a container element on the fly and append a bunch of divs to it.
const wrapper = document.createElement('div');
wrapper.style.display = 'flex';
wrapper.style.position = 'absolute';
text.forEach((t) => {
const d = document.createElement('div');
d.textContent = t.headerName;
wrapper.appendChild(d);
});
document.body.prepend(wrapper);
So it’s all rendered into a structure like this:
ff | other | col2andmore |
Now I need to get the width of each element. I do it like this:
const data = Array.from(wrapper.childNodes).map((n) => {
return {
width: n.offsetWidth,
}
});
I’m worried about the performance. I may have tens of thousands of those divs. I know that when reading offsetWidth
browser has to run styles recomputes. I’m wondering what’s the most effecient way to get those numbers from divs? I assume that since the container is absolute
the recompute will be limited to only this div and its children, not the entire page.
What are your thoughts or suggestions?
Solution:
Doing a quick test here, mapping offsetWidth
inside a loop is very fast.
Below is an example, for me it’s about 7ms, the majority of the time is creating the 1000 elements (ps, there are ways to speed that up too).
for (let l = 0; l < 1000; l ++) {
const s = document.createElement('span');
s.innerText = `ref:${l} `;
document.body.appendChild(s);
}
console.time('t1');
const m = [...document.querySelectorAll('span')]
.map(m => m.offsetWidth);
console.timeEnd('t1');
console.log(`size of element 0: ${m[0]}`);
console.log(`size of element 999: ${m[999]}`);
In the above profile you can see there are 0 reflow’s during the map
. The next layout calc is about 0.34ms after the console.timeEnd
and this reflow is only because SO snippets rendering the log.
On the other hand if your dirty the DOM inside the map, you get a massive slowdown. Quick test 1400ms, IOW: 200 times slower.
And below this is what the profile looks like if you dirty the DOM inside the map,. See all those purple blocks, are forced reflows, and the red marks are even Chrome warning it’s a likely performance bottleneck.