All versions of IE (including 10) appear to hold on to a significant amount of memory allocated by iframes until window.top.unload occurs. This creates quite the challenge f
You are missing one important step: After setting the src to 'about:blank', you need to listen to the load of 'about:blank', and only then remove your iFrame.
In IE 11, just setting iframe.src = 'about:blank'
seems to fix this. Otherwise, you can watch the memory grow forever in the F12 Memory tab, even if you're removing iframes from the DOM and letting them be garbage collected. If you blank the iframes first, you see the memory go up and down as you'd expect.
I put together a jQuery plugin for cleaning iframes that prevents memory leaks in some cases:
(function($) {
$.fn.purgeFrame = function() {
var deferred;
if ($.browser.msie && parseFloat($.browser.version, 10) < 9) {
deferred = purge(this);
} else {
this.remove();
deferred = $.Deferred();
deferred.resolve();
}
return deferred;
};
function purge($frame) {
var sem = $frame.length
, deferred = $.Deferred();
$frame.load(function() {
var frame = this;
frame.contentWindow.document.innerHTML = '';
sem -= 1;
if (sem <= 0) {
$frame.remove();
deferred.resolve();
}
});
$frame.attr('src', 'about:blank');
if ($frame.length === 0) {
deferred.resolve();
}
return deferred.promise();
}
})(jQuery);
This code handles cross-origin frames by updating the frame src to "about:blank" before cleaning its content. To use the plugin, call $frame.purgeFrame()
where you would otherwise call $frame.remove()
.
As Josh points out, iframes that display an image seem correlated with memory leaks. For example, creating iframes pointing to google.com will produce a memory leak in IE7 and IE8. Using the plugin above prevents those leaks.
Unfortunately that plugin is not effective in all cases. It does not seem to help much with iframes pointed at //en.wikipedia.org/wiki/Memory_leak.
The code that I used for testing memory leaks and for testing the above plugin is at https://gist.github.com/3125807
As Josh says, the memory leaks are actually pseudo-leaks in IE8. However in IE7 memory is not reclaimed, even when the parent window unloads.
Have a try with this:
collectGarbageForIframe: function() {
var $iframes = $("*[tag='iframe']");
$iframes.each(function() {
var $target = $(this);
if($target.length>0) {
$target[0].src = "about:blank";
$target[0].contentWindow.document.write('');
$target[0].contentWindow.close();
$target.remove();
if( typeof CollectGarbage == "function") {
CollectGarbage();
}
}
});
}