How to reduce/remove memory leaks in Angular appli

2020-05-11 10:47发布

I am optimizing my large Angular App. As I found a that Google DevTools is very good to detect problems. As I just have started learning about DevTools, I am very confused about memory leaks.

When I move back and from to different pages in my app, Profile heap Snapshot size is increasing again and again so I think there are some object which is not being cleaned by GC and that's why my app is getting slow after sometime so how to solve this. Please help.

Note

This is what I understand using DevTools, please correct me if I am wrong. Other suggestions are welcome.

Till now what I have used

  1. AngularOnce directive for reducing watch whenever required.
  2. QuickList directive to replace ng-repeat with quick-ng-repeat.
  3. InView Directive, to handle large list so I am removing DOM which is not in viewport.
  4. Lazy load approach from ngInfiniteScroll directive.

1条回答
仙女界的扛把子
2楼-- · 2020-05-11 11:23
  1. Remove bindings to avoid memory leaks, Use Scopes $destroy() Method.

    Note:

    The most likely culprit of memory leak in Angular is JQuery used in your directives. If you attach an event-listener in your directive using a JQuery plugin, the latter would keep a reference to your DOM even after Angular deletes its own reference to the DOM, which means it would never be garbage-collected by the browser, which in turn means “Detached DOM tree” in your memory

    In your Directive keep practice for unbinding the jQuery Event. $destory Method which can be used to clean up DOM bindings before an element is removed from the DOM.

     $scope.$on("$destroy",function() {
        $( window ).off( "resize.Viewport" );
     });    
    
  2. Don't Forget To Cancel $timeout Timers In Your $destroy Events In AngularJS

    $scope.$on("$destroy",function( event ) {
        $timeout.cancel( timer );
    });
    
查看更多
登录 后发表回答