Iframes and memory management in Javascript Iframes and memory management in Javascript javascript javascript

Iframes and memory management in Javascript


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

<a href="#">Remove</a><iframe src="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 from localStorage}


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:

var object = {};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.


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