Avoiding memory leaks loading content into an iframe

旧巷老猫 提交于 2020-01-12 08:43:32

问题


I am working on an embedded system that presents content in an iframe. It uses signalR (which is based on ajax) and jquery. The browser gets slower and slower, and the memory usage goes up and up, as the hours go by. So I am looking to remove all potential memory problems.

When the new page is loaded into the iframe, I attach click and focus event handlers.

Just before the iframe page is to be replaced, I un-attach them.

However, if I inspect $.cache (while testing on a PC with firefox, so not completely the same as my real system) it still shows $.cache gaining more and more elements each time the iframe is reload.

Is this the correct way to do things? Is there anything else I can try? Why is $.cache growing?

(In case your are interested I am using a raspberry pi (runs linux) with the Midori browser, though there is a choice of other (mostly web-kit) browsers that I could use).

Javascript I use to change the iframe contents...

hubProxy.client.loadPage = function (pageFilename, pageType) {
    frameNode = $("#myIframe").contents();
    $("a", frameNode).off();  
    $("#myIframe")[0].src = pageFilename;
};

回答1:


Write a wrapper div to hold your iframe container, such as...

<div id="myIframeWrapper"></div>

Now you can clean up after the previous iframe page, and this can be done by completely clearing out everything in the DOM related to the previous iframe, and then creating a fresh iframe by using a constructor when you invoke your loadPage function.

hubProxy.client.loadPage = function (pageFilename, pageType) {

    var myNewIframe = '<iframe id="myIframe" src="' + pageFilename + '"></iframe>';

    // Remove old iframe from the DOM and replace with new iframe
    if ($("#myIframe")) {
        $("#myIframeWrapper").empty().append( myNewIframe );
    }

    var frameNode = $("#myIframe").contents();
    $("a", frameNode).off();
};

You will notice that the original line assigning the iframe source has been removed, as it is already accounted for in the new constructor. This also has the benefit of being able to add other iframe attributes using the constructor, such as the iframe size, etc.



来源:https://stackoverflow.com/questions/18644462/avoiding-memory-leaks-loading-content-into-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!