Why is the following plunkr causing a memory leak every time $compile runs?
http://plnkr.co/edit/HhB4croPKuN5TP2NPqq6
I am writing a directive which sometimes needs to completely re-render its HTML. It does this by generating its template as a string, and then feeding that string to $compile, finally using jQuery to remove the old DOM and replace it with the newly rendered element.
Each time it does this, the application leaks several megabytes of memory, often crashing the browser. The Chrome heap snapshot shows a tree of detached DOM elements gets added each time, but the Plunkr for some reason does not have this issue (although it still leaks a lot).
What am I doing wrong that causes this memory leak?
This is clearly not the way Angular directives are meant to be written, I know. My first approach would be a combination of ng-repeats with other two-way binding. Unfortunately, this causes performance issues as the number of $watch-statements on the scope increases. For a bit of reasoning as to why I chose this approach, I give a small rant about it here: How does data binding work in AngularJS?
I have been working on the plunk, and it no longer leaks memory. I'll keep this question around, in case anyone else finds it useful as a non-leaking method for re-compiling DOM.
Here are a few things that might cause memory leaks in an Angular app: Missing unsubscription, which will retain the components in the memory. Missing unregistration for DOM event Listeners: such as a listener to a scroll event, a listener to forms onChange event, etc.
Answered it myself to make sure it doesn't crop up under "unanswered". I have been working on the plunk, and it no longer leaks memory. I'll keep this question around, in case anyone else finds it useful as a non-leaking method for re-compiling DOM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With