javascript - Javascript 中的 iframe 和内存管理

标签 javascript jquery memory-management iframe

我有将页面加载到 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 here .

此外,您也可以进行手动清理 - 即,如果您的 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
}

关于javascript - Javascript 中的 iframe 和内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12128458/

相关文章:

javascript - jQuery - 悬停时停止自动滚动 div

jQuery 非选择器和实时绑定(bind)

ios - 呈现的 UIViewController 没有在解雇时被释放

linux - 内核页面是否被换出?

javascript - 检测鼠标左键按下

javascript - 使用 Google Earth Engine 将每日数据减少到每月

javascript - 如何创建动态变量并从 json 获取动态数据

javascript - Node.js:http 完成事件、响应关闭事件和响应结束事件之间的区别

javascript - 在列中显示嵌套的 HTML ul 列表

objective-c - iOS内存管理问题