简体   繁体   中英

Angular.js and javascript management

I have recently sarted using angular and I have a quick question. I can't seem to find a direct answer through searching (it's very possible I'm searching it wrong so bear with me).

I am building a rather large single page web app and at my first stab at it I noticed the javascript was causing a memory leak. I realized it was because I was bringing in new javascript with each page change (in the new content brought in via ajax), and it was sitting in a detached dom tree.

I am trying a second approach where I use angular (for an incredible amount of reasons - mainly it makes making these apps a million times easier. But I a wondering how angular addresses this issue.

Let's say I run all my functionality through angular except things like fancy animations/transitions. If i had scripts for each new page (on each page), would I have the same issue using angular? Is there a better way to handle this and/or manage javascript usage on a SPA?

Any direction would be much appreciated, thanks!!!

You'd absolutely have the same issues with Angular. Probably even worse, as Angular's DOM manipulations give you plenty of opportunities to mess up memory management with detached DOMs.

As you get into writing custom directives, make sure you're using the $destroy event to clean up any references to the DOM; this is the first thing I look for with leaks in Angular.

$scope.$on('$destroy', function() {

  // Nullify any references that might hold onto a DOM tree.
  $someCachedElement = null;
  $someOtherThing = null;

  // Make sure you're unsubscribing from any custom services you've written that
  // might also be referencing your directive elements.
  someService.remove($scope);

  // Maybe you used a jQuery plugin on $el. Hopefully it has a destroy method.
  $el.somePlugin('destroy');
});

But in general, this is the same advice I'd give for a traditional SPA; any component / module / class that interfaces with the DOM should have teardowns that do this type of thing. And ideally, tests proving that the teardowns always fire when you expect them to. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM