Best time to update scroll position to minimize visual changes
CodeWithOz opened this issue · 2 comments
I have a scenario where I want to render a list at a certain scroll position that's not 0
. If I update scroll after rendering the list, I can see a brief period where the list is at scrollTop = 0
, before it changes to the new scrollTop
value. This corresponds to code like this:
const listHtml = '<ul>...</ul>'
requestAnimationFrame(() => {
listContainer.innerHTML = listHtml;
setTimeout(() => listContainer.scrollTop = nonZeroValue, 0);
});
This brief period looks like a flash of content because it's so quick. To prevent it, I set the scroll position directly inside rAF immediately after rendering the list items. So that code above became this:
const listHtml = '<ul>...</ul>'
requestAnimationFrame(() => {
listContainer.innerHTML = listHtml;
listContainer.scrollTop = nonZeroValue;
});
This took away the flash, the scroll position is set immediately the items are rendered. However, this significantly slows down the time it takes to actually paint the rendered list items.
So my question is what's the right time to update scroll position to both avoid the flash and minimize the delays to layout/painting?
Thanks for the suggestion! Yeah using opacity like that won't be ideal.