开发者

Is it possible to destroy loaded JavaScript, including function & local variable?

I know. It is possible to dynamically load JavaScript and style sheet file into header of document. In the other hand, it is possible to remove script and style sheet tag from header of document. However, loaded JavaScript is still live i开发者_JAVA百科n memory.

Is it possible to destroy loaded JavaScript from web browser memory? I think. It should be something like the following pseudo code.

// Scan all variables in loaded JavaScript file.
var loadedVariable = getLoadedVariable(JavaScriptFile);

for(var variable in loadedVariable)
{
    variable = null;
}

// Do same thing with function.

Is it possible to create some JavaScript for doing like this?

Thanks,

PS. Now, you can use xLazyLoader and jQuery for dynamic loading content.


If the loaded script is assigned to a window property, for instance with the module pattern like so:

window.NiftyThing = (function() {
    function doSomething() { ... }
    return {
        doSomething: doSomething
    };
})();

or

window.NiftyThing = {
    doSomething: function() { ... }
};

or

NiftyThing = {
    doSomething: function() { ... }
};

Then you can delete the property that references it:

delete window.NiftyThing;

...which removes at least that one main reference to it; if there are other references to it, it may not get cleaned up.

If the var keyword has been used:

var NiftyThing = {
    doSomething: function() { ... }
};

...then it's not a property and you can't use delete, so setting to undefined or null will break the reference:

NiftyThing = undefined;

You can hedge your bets:

NiftyThing = undefined;
try { delete NiftyThing; } catch (e) { }

In all cases, it's up to the JavaScript implementation to determine that there are no outstanding external references to the loaded script and clean up, but at least you're giving it the opportunity.

If, as Guffa says, the loaded script doesn't use the module pattern, then you need to apply these rules to all of its symbols. Which is yet another reason why the module pattern is a Good Thing(tm). ;-)


It might be possible to remove a Javascript file that has been loaded, but that doesn't undo what the code has done, i.e. the functions that was in the code are still defined.

You can remove a function definition by simply replacing it with something else:

myFunction = null;

This doesn't remove the identifier, but it's not a function any more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜