Javascript memory leak on page refresh; remedy?

2019-01-26 19:05发布

问题:

I am experiencing a memory leak in IE that occurs upon a page refresh (as I described in this SO post).

All I want to know at this point is: is there a way, on the document "unload" event (which could get called when the page refreshes or closes), to clear EVERYTHING? I'm looking for a simple solution that would ensure that everything gets destroyed in order to avoid the leak. Is this even possible, or do I have to continue looking into the details of the leak and fixing it on an object by object basis?

Update: Ok maybe I wasn't descriptive enough. I can't (at least I dont think I can) just set all of my objects to null: I have event handlers for click events etc. so the application needs to be "live" constantly until it is closed. Also if I then think about just nulling everything out in an "unload" method (called when the page is exited), then all my objects would have to have global scope (right)? What is the best way to remedy this? Is there a way to get a list of all referenced objects so I can null them? Should I add every object I use to an array so that I can dereference it later?

回答1:

try window.onbeforeunload or window.onunload and set the variables you use to null. or you looking for something more?



回答2:

Set your objects to null and they won't be leaked.



回答3:

check if you are using a random anti-cache URL parameter, it might cause memory leaks

  • IE tries to keep all scripts loaded from the same domain in memory as you navigate from page to page, because there is a high chance that being on different pages you will be needing pretty much the same scripts.
  • a random anti-cache parameter added to the URL of a script makes it a different script (at least caching is fooled by that)
  • as we know IE tries to load all possible scripts for the domain and keep them
  • a random anti-cache parameters leads to memory leaks because every time otherwise the same scripts have a different URL and IE thinks they are different and downloads them over and over on each reload and keeps them in memory