spiderplant0
spiderplant0

Reputation: 3952

Avoiding memory leaks loading content into an iframe

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

Upvotes: 4

Views: 8726

Answers (1)

Epiphany
Epiphany

Reputation: 1894

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.

Upvotes: 3

Related Questions