Search code examples
javascriptangularperformancelistvirtual

Performance optimizations for virtual lists in Angular


I' am building a virtual list in Angular and while I have implemented most of the things (displaying only necessary items based on scroll position, keeping accurate scroll position etc.), there is one last thing I' am looking to fix.

As the number of JavaScript objects grow the page starts lagging a bit. Keeping items in JavaScript arrays is vital to get them rendered and to calculate positions etc. What would be the best strategy to ease memory load for browser's main thread? Can we reduce browser's main thread's memory usage by moving off JavaScript objects to say Web Workers so that whenever we need items we could ask them. What would be the practical limitations of this approach?

Are there other solutions we could use?

I have looked into many tutorial for virtual lists and none of them has pointed some solution to tackle memory usage.


Solution

  • For performance improvment you can use requestAnimationFrame and zone.js.

    With zone.js you can simulate something like multithreading and put you calculation to "second" javascript process.

    Inject NgZone in your component:

    constructor(private readonly zone: NgZone) { }
    

    Then you can run you calculation in "second" process like this:

    this.zone.runOutsideAngular(() => {
          requestAnimationFrame(() => this.calculateFunction());
    });
    

    Here is a very good implementation of virtual scroll dom for angular. Try it or look at the source code.