Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IFrame Memory Leak when adding/removing IFrames

I have the following HTML that can reproduce the issue I'm seeing. As I add/remove IFrames over time the browser is never releasing the IFrame memory. As a result the memory grows and grows overtime which results in degraded performance. I have seen this impact Safari/IE11/Edge quite a bit while Firefox/Chrome handle it better. Does anyone have any tips on how to circumvent the IFrame memory leak?

<html>
<body>
<button onclick="add()">ADD</button>
<button onclick="remove()">REMOVE</button>
    <script>
  function add() {
    var ifrm = document.createElement('iframe');
    ifrm.setAttribute('id', 'ifrm');
    ifrm.setAttribute('src', 'http://somewebsite.com');
    document.body.appendChild(ifrm);
  }
  function remove() {
    document.body.removeChild(document.getElementById('ifrm'));
  }
    </script>
</body>
</html>
like image 257
Kyle Avatar asked Jan 18 '18 22:01

Kyle


People also ask

What is detached dom?

Detached DOM elements are the elements which have been removed from the DOM but their memory is still retained because of JavaScript. This means that as long the element have a reference to any variable or an object anywhere, it does not garbage collected even after destroyed from the DOM.

What is memory leak in rails?

Tony Rowan on Jul 26, 2022. A memory leak is an unintentional, uncontrolled, and unending increase in memory usage. No matter how small, eventually, a leak will cause your process to run out of memory and crash.

What is memory leak in JavaScript?

What are memory leaks? In simple words, a memory leak is an allocated piece of memory that the JavaScript engine is unable to reclaim. The JavaScript engine allocates memory when you create objects and variables in your application, and it is smart enough to clear out the memory when you no longer need the objects.


1 Answers

Try these operations:

  1. set the iframe url to blank page, such as "";
  2. break your page's refs which may ref to the objects of iframe page;
  3. set all objects created by the iframe page to null or undefined.

Operation 2 and 3 are available only if the iframe's page is developed by yourself.

If you did 1 and 2, then the chrome will release the js heap immediately which is allocated by the iframe page.

If you did 1, 2 and 3 then the firefox will release the js heap immediately too.

But, even if you did all the operations above, the Safari won't release the js heap in a period.

like image 91
yonghu Avatar answered Oct 17 '22 14:10

yonghu