DIV CSS 佈局教程網

解決 IE 瀏覽器 IFrame 對象內存不釋放的問題
編輯:關於JavaScript     

項目組發現:在使用 showModalDialog 彈出的窗體中,如果包含 IFrame 對象,則 IFrame 占用的內存資源在窗體關閉後不會釋放。反覆彈出關閉多次後,IE 的內存占用可超過數百 MB,嚴重時甚至報錯且無法關閉,只能殺進程重啟瀏覽器。經測試,用 open 方式彈出也存在同樣問題。

在 IE8 中,open 與 showModalDialog 彈出的內存占用有差異:open 彈出的窗體占用一個獨立的 iexplorer.exe 進程;showModalDialog 彈出的窗體則與父窗體共用同一個進程。

搜索後找到的解決辦法是:在窗體關閉前,從文檔中刪除 IFrame 對象,代碼如下:

 var el = document.getElementById("scanIf");
 el.src="";
 el.contentWindow.document.write('');
 el.contentWindow.document.clear();
 var p = el.parentNode;
 p.removeChild(el);

但測試時發現兩個限制:

1. el.src 可能還沒執行完就執行了後面的語句,如果 IFrame 中包含跨域內容,會提示沒有權限;

2. 窗體關閉得比腳本執行快,內存仍然沒有釋放。

經過修改,最終腳本如下:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 <HTML><HEAD><TITLE></TITLE>
 <BODY onbeforeunload="return unloadHandler();">
 <IFRAME id="scanIf" width="800px" height="600px" src = "https://www.baidu.com"></IFRAME>
 <SCRIPT type="text/javascript">
 function unloadHandler(notip) {
 // 取消窗口關閉時的監聽事件
 document.getElementsByTagName("BODY")[0].onbeforeunload = null;
 var el = document.getElementById("scanIf");
 if (el) {
 el.src = "";
 setTimeout(cycleClear, 100);
 return "提示:請點擊取消按鈕,當前窗口會自動關閉。";
 }
 return true;
 }
 function cycleClear() {
 try {
 var el = document.getElementById("scanIf");
 if (el) {
 el.contentWindow.document.write('');
 el.contentWindow.document.clear();
 var p = el.parentNode;
 p.removeChild(el);
 }
 window.close();
 } catch (e) {
 setTimeout(cycleClear, 100);
 }
 }
 //window.onunload = unloadHandler;
 </SCRIPT>
 <input type="button" value="remove" onclick="unloadHandler();">
 </BODY></HTML>

通過 onbeforeunload 延遲關閉、再用 setTimeout 確保清理腳本執行完畢,最終得以在關閉前徹底移除 IFrame,成功釋放內存。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved