[英]Iframes and memory management in Javascript
我有鏈接將頁面加載到iframe中。 我一直在使用Google Chrome的內存堆分析器監視內存中數據的累積,我注意到內存中有一些泄漏。
我加載了頁面並拍攝了第一張快照,最多增加了2.69 MB
。 我點擊了將頁面打開到iframe的鏈接,並拍了另一張快照,總共給了我14.58 MB
。 我使用以下jquery代碼段刪除了iframe:
$('#myframe').unbind();
$('#myframe').remove();
/*
* By the way, I also tried $('#myframe > *') as a selector.
* It still didn't work. Even if it would, it doesn't look like a viable solution to me.
* It looks too resource intensive.
*
* I forgot to mention that I am not using Ajax to load my pages
*/
我拍了另一張快照,得到了5.28 MB
,這表明與初始值的偏差為2.59 MB
,根據我的理解,這表明內存泄漏。
現在,我的問題是:如果我刪除iframe(其中包含加載的文檔)不是垃圾收集器發現有必要從內存中刪除該文檔中包含的所有對象嗎? 或者我必須手動執行此操作嗎?
我認為如果我將文檔加載到iframe中,它的大小不會影響父頁面上的內存使用。 我雖然它將被視為一個單獨的窗口,但顯然我不是一個明智的假設。
有關如何解決這個問題的任何建議?
謝謝。
在iframe中,在刪除之前觸發重新加載,然后將其刪除。
<a href="#">Remove</a>
<iframe src="url" />
$('a').click(function(){
$('iframe')[0].contentWindow.location.reload();
setTimeout(function(){
$('iframe').remove();
}, 1000);
});
DEMO在這里 。
另外,您也可以進行手動清理 - 即,如果您的cookie或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
}
如果在主窗口的對象中引用iframe中的任何對象,則該對象將不會從DOM中刪除,因此,如果您有類似這樣的內容:
主窗口:
var object = {};
function iframe_call(data){
object.iframe_data = data.something
}
IFRAME:
function onClick(){
parent_object.iframe_call(this);
}
如果您引用DOM對象,則會發生這種情況。
var frame = document.getElementById("myframe");
frame.src = "about:blank";
這對我有用,可以防止內存泄漏。 你必須銷毀iframe的父節點,做一些延遲以防止內存泄漏
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.