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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…