Skip to content Skip to sidebar Skip to footer

Iframes And Memory Management In Javascript

I have links that load pages into iframes. I have been monitoring the accumulation of data in memory using Google Chrome's memory heap profiler and I noticed some leaks in memory.

Solution 1:

In the iframe, trigger a reload before removing it and then remove it.

<a href="#">Remove</a>
<iframesrc="url" />​

$('a').click(function(){
    $('iframe')[0].contentWindow.location.reload();
    setTimeout(function(){
       $('iframe').remove();
    }, 1000);
});​

DEMO here.

Addionally, you can do a manual cleaning up too - i.e. if you have data in your cookies or HTML5 localStorage.

window.onbeforeunload = function(){
    $(document).unbind().die();    //remove listeners on document
    $(document).find('*').unbind().die(); //remove listeners on all nodes//clean up cookies
    /remove items fromlocalStorage
}

Solution 2:

If any objects from the iframe is referenced in a object in the main window that object won't be removed from the DOM, so, if you have something like this:

Main window:

varobject = {};
function iframe_call(data){
    object.iframe_data = data.something
}

iframe:

function onClick(){
    parent_object.iframe_call(this);
}

this happens especially if you refer DOM objects.

Solution 3:

var frame = document.getElementById("myframe");
frame.src = "about:blank";

This worked from me and prevented memory leaks. Ig you must destroy the parent of the iframe, do it with some delay to prevent memory leak

Post a Comment for "Iframes And Memory Management In Javascript"