menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

150 lines ...
source image

Dev

1w

read

135

img
dot

Image Credit: Dev

150 lines or less - implementing virtual scroll for web from scratch

  • Virtual scroll, also known as virtualization or windowing, efficiently renders large lists in web applications by only loading visible items in the viewport.
  • The implementation involves removing items outside the viewport from the DOM and adding new ones on-demand for smooth scrolling.
  • Using ReactJS, a reusable component for virtual scroll can be created following specific principles that can be applied to any framework or vanilla JS.
  • Initial steps include preparing a large list with random data and defining window size, row height, and data array for the virtual table.
  • The core idea involves providing a fixed-size container for scrolling, calculating indexes based on scroll position, and maintaining desired scroll position using divs.
  • Basic implementation includes tracking scroll position, calculating start and end indexes for shown items, and maintaining a list of rendered rows.
  • Optimizations like buffering rows above and below the viewport and throttling scroll updates are crucial for smoother performance and reduced DOM churn.
  • Buffering involves rendering extra rows around the viewport to prevent a snapping effect when items enter and exit the view.
  • Throttling scroll updates helps in controlling state updates and improving performance by limiting the frequency of updates during rapid scrolling.
  • The final implementation can be tested using jsPad, with possibilities for further enhancements and optimizations to make the virtual scroll more generic and performant.

Read Full Article

like

8 Likes

For uninterrupted reading, download the app