Tala
Tala

Reputation: 927

Unload a Javascript from memory

I am thinking of a web application on browsers. I can dynamically add required js files as needed while traversing through different parts of application, but can I unload unnecessary js content from the current session's "memory" as the memory usage grows over time?

I know it is possible to remove the tag responsible for the content but it is not assured that it will eventually unload and unbind everything correspondent to that content.

Thanks

Upvotes: 14

Views: 6284

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

I know it is possible to remove the tag responsible for the content but it is not assured that it will eventually unload and unbind everything correspondent to that content.

In fact, it's assured that it will not. Once the JavaScript is loaded and executed, there is no link between it and the script element that loaded it at all.

You can dynamically load and unload modules, but you have to design it into your code by

  • Having a module have a single symbol that refers to the module as a whole
  • Having an "unload" function or similar that is responsible for removing all of a module's event listeners and such

Then unloading the module is a matter of calling its unload function and then setting the symbol that refers to it to undefined (or removing it entirely, if it's a property on an object).

Here's a very simple demonstration of concept (which you'd adapt if you were using some kind of Asynchronous Module Definition library):

// An app-wide object containing a property for each module.
// Each module can redefine it in this way without disturbing other modules.
var AppModules = AppModules || {};

// The module adds itself
AppModules.ThisModule = (function() {
    var unloadCallbacks = [];

    function doThis() {
        // Perhaps it involves setting up an event handler
        var element = document.querySelector(/*...*/);
        element.addEventHandler("click", handler, false);
        unloadCallbacks.push(function() {
            element.removeEventHandler("click", handler, false);
            element = handler = undefined;
        });

        function handler(e) {
            // ...
        }
    }

    function doThat() { 
        // ...
    }

    function unload() {
        // Handle unloading any handlers, etc.
        var callbacks = unloadCallbacks;
        unloadCallbacks = undefined;
        callbacks.forEach(function(callback) {
            callback();
        });

        // Remove this module
        delete AppModules.ThisModule;
    }

    return {
        doThis: doThis,
        unload: unload
    };
})();

That callbacks mechanism is very crude, you'd want something better. But it demonstrates the concept.

Upvotes: 10

Related Questions