Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

jquery - Iframes and memory management in Javascript

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.

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
*/

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.

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?

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?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});?

DEMO here.

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...