Javascript 中的 iframe 和内存管理 [英] Iframes and memory management in Javascript

查看:15
本文介绍了Javascript 中的 iframe 和内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有将页面加载到 iframe 的链接.我一直在使用 Google Chrome 的内存堆分析器监视内存中数据的积累,我注意到内存中存在一些泄漏.

I have links that load pages into iframes. I have been monitoring the accumulation of data in memory using Google Chrome's memory heap profiler and I noticed some leaks in memory.

我加载了页面并拍摄了第一个快照,总计 2.69 MB.我单击了将页面打开到 iframe 的链接,并拍摄了另一个快照,总共给了我 14.58 MB.我使用以下 jquery 代码段删除了 iframe:

I loaded the page and took the first snapshot which added up to 2.69 MB. I clicked the link that opens a page into an iframe and took another snapshot giving me 14.58 MB in total. I removed the iframe using the following jquery snippet:

$('#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的偏差,根据我的理解,这表示内存泄漏.

I took another snapshot and got 5.28 MB which indicated a deviation of 2.59 MB from the initial value, which according to my understanding indicates memory leackage.

现在,我的问题是:如果我删除一个 iframe(其中包括加载到其中的文档),垃圾收集器是否也需要从内存中删除该文档中包含的所有对象?还是我必须手动执行此操作?

Now, my question is: If I remove an iframe (which includes the document loaded in it) doesn't the garbage collector find it necessary to also remove all the objects contained in that document from memory? Or will I have to do this manually?

我认为如果我将文档加载到 iframe 中,它的大小不会影响父页面上的内存使用.虽然我认为它会被视为一个单独的窗口,但显然我认为这不是一个明智的假设.

I thought that if I load a document into an iframe, it's size will not affect the memory use on the parent page. I though it will be considered a separate window, but obviously that wasn't a well informed assumption on my part.

关于如何解决这个问题有什么建议吗?

Any suggestions on how to tackle this?

谢谢.

推荐答案

在 iframe 中,在移除之前触发重新加载,然后再移除.

In the iframe, trigger a reload before removing it and then remove it.

<a href="#">Remove</a>
<iframe src="url" />​

$('a').click(function(){
    $('iframe')[0].contentWindow.location.reload();
    setTimeout(function(){
       $('iframe').remove();
    }, 1000);
});​

此处演示.

此外,您也可以进行手动清理 - 即如果您的 cookie 或 HTML5 localStorage 中有数据.

Addionally, you can do a manual cleaning up too - i.e. if you have data in your cookies or 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 中的 iframe 和内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆