javascriptperformancescroll-lock

Performance enhancement of this one line of Javascript code


el.style.top = document.body.scrollTop + 'px';

I'm using this to lock the scrolling of some TH elements vertically. This line of code seems to have exponential runtime complexity. It works nicely when I am locking 10 elements. 30 elements, it's still responsive but very bad. 60 elements, it becomes unresponsive.

In case you're wondering. No, I do not have it called repeatedly. It is called exactly 3 times per scroll.

Solved: The problem was in document.body.scrollTop. After trying to scroll the elements up and down the page using a pre-calculated value, it is smooth, but when adding that dummy call into the same function, it became unresponsive.


Solution

  • Depending on what your style.top assignment affects and how the browser rendering engine works, each access to .scrollTop might trigger a reflow. So you should access it only once before the loop over your elements and store it in a variable:

    const { scrollTop } = document.body;
    for (const el of els) {
        el.style.top = scrollTop + 'px';
    }