Unload a Javascript from memory

前端 未结 1 714
执念已碎
执念已碎 2021-01-04 20:19

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 u

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-04 20:33

    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.

    0 讨论(0)
提交回复
热议问题