Can I Use Iframe To Solve Memory Leak?

- 1 answer

I am using a very complex and compressed js library, and it create a complexly structured object with lots of event and interval running in it. I feel its function destroy() is broken, things are still running and memory is hold, which causes memory and makes the website crash in weaker device like mobile.

As I can't fixed function destroy(), I am thinking if there is a way to remove the whole object in force. Can I use iframe to do that? And how? If the parent html create an iframe and store this complex object in iframe content, does the website remove the whole object when the iframe load another webpage?



Your question is extremely general so all we can really do is answer very generally.

Yes. Removing an iframe or loading a new document into it will free the entire Javascript and DOM context from the original iframe document. The only things that could persist are things written to LocalStorage or things put into a cookie. The regular Javascript and DOM context will be cleaned up (in any well-behaved browser).

I should add that freeing the memory used by these resources will not necessarily return all that memory to the Operating System, but it will at least be free for reuse within the browser and should prevent a buildup of memory over time (due to that resource). When exactly memory is returned back to the operating system depends entirely upon internals of both the operating system and the specific browser design on that operating system (and how they both manage memory).

It feels like using that to solve a memory leak (while perhaps feasible) is a giant hack and is likely not even close to the best way to solve your problem. But, since you've shared basically zero details about what is actually causing the problem, we can't really dive into the better options for solving your specific problem.

It feels like if you know what is causing the leak well enough to move it to another iframe, then you can probably just fix the leak directly. Modern browsers are pretty darn good about leaks caused by bugs so any leak you think you're seeing is probably just your code accumulating some sort of object rather than releasing references to it so it can be garbage collected.

I'd suggest you ask a different question about how to fix your memory leak and include as many details about what you know and how your code works (including actual code) and, at worst, you will get some advice on how to further track down what is leaking. At best, folks will be able to advise you on how to actually fix the leak.