How virtual / infinite scrolling works

June 02, 2017 0 Comments

How virtual / infinite scrolling works



You may ask why should I ever read about how virtual scrolling is done and You’re partly right. There are numerous libraries that solve the problem for us but still there are times when those solutions are simply not enough so it’s worth knowing how they work.

So what is this fuss about virtualizing scrolling in browsers?

The main problem is that altering anything in the DOM is excruciatingly slow compared to other operations you can do in the browser.

You may ask why? Because whenever we add/remove/update something in the DOM the browser will have to recalculate the layout, re render etc. So all in all it’s just slow.

Even worse a huge DOM means even more data that the browser will have to calculate with.

Okay so the DOM can be slow. When does it really affects us?

For example when we’re trying to show long lists to the website’s user. Showing a long list not only means many elements in the DOM but as it possibly requires scrolling it will cause layout calculation and rendering quite often.

To summarize: Showing long scrollable lists with many items on a website will kill the user experience.

So how can we avoid adding too many elements to the DOM?

  • As a user can only see a limited amount of rows in a list why not just add those elements visible to the user to the DOM. We usually call a frame where visible content can be found a ViewPort.
  • Okay this is great but when I scroll the other elements won’t show in the list.
  • So when should we add the other elements to the DOM?
  • We should add the remainder rows of the list to the DOM only when they’ll become visible by subscribing to the “scroll” event of the element containing the list often called as ViewContainer.
  • Okay seems much better but when I scroll waaay down it becomes slow again :(
  • The problem is that the DOM gets quite big after scrolling. So to solve this we should also remove rows when they scroll away from the ViewPort.
  • Great now it’s fast but when I scroll often I see blank areas.
  • We can fix that by adding additional rows before and after the viewport so when the user scrolls the browser has time to render the new rows to show.

So that’s how infinite / virtual scrolling works.

You can check our this angular2-cool-infinite-grid an infinitely scrolling grid I wrote for angular.

See the cool interactive DEMO here.

Hope you find this package useful.

Thanks for reading.

Tag cloud