Blog>
Snippets

Optimizing Scrolling Performance with Adaptive Padding

Explain a strategy for improving scrolling performance in a virtualized list by adaptively adjusting padding based on the scrolling speed, reducing layout shift and enhancing the user's scrolling experience.
let lastScrollTop = 0;
let padding = 0; // starting padding value
Initialize variables to store the last scroll position and the current padding.
function adjustPaddingBasedOnSpeed() {
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop;
  const scrollSpeed = currentScrollTop - lastScrollTop;

  padding += scrollSpeed > 0 ? 20 : -20; // Increase or decrease padding based on scroll direction
  padding = Math.max(0, padding); // Ensure padding does not become negative

  document.querySelector('.virtual-list').style.paddingTop = `${padding}px`;
  lastScrollTop = currentScrollTop;
}
Calculates scroll speed and adjusts padding accordingly. Adds padding when scrolling down and reduces when scrolling up to minimize layout shifts.
window.addEventListener('scroll', adjustPaddingBasedOnSpeed);
Attaches the padding adjustment function to the scroll event to dynamically adjust padding as the user scrolls.