Dynamically loading and deleting JS code from DOM and memory
Basically i want to load JS file like this into the page dynamically
globalVar = "some variable";
alert(globalVar);
And then i want to remove it, i can easily delete script from DOM, but i will have globalVar
remain in the memory...
Is there a JS libraries that will help me to load script and then unload it and unload all variables, classes, functions that were declared by that script? Or is there some tricks to开发者_运维知识库 do that?
In JavaScript, when you declare a global variable it is actually a property of the "global" object (usually the DOMWindow, or "window"), so you can simply delete the property by the name of the variable to delete the global reference. For example:
var foo = 123;
alert(foo); // Alerts "123"
alert(window.foo); // Alerts "123"
delete window.foo;
foo; // ReferenceError: foo is not defined.
So if you can keep track of the global variables you use (which should be very, very few, like one) you can just delete it as a property from the "window" or "global" root-level objects.
Update
You can extend this idea to work generally as follows. At the beginning of your script, enumerate the properties of the global object and store them in a reference object. Then, when you want to identify newly added globals, enumerate the global properties again and store only the ones which do not exist in the reference object (meaning they were newly added since you last checked). Then simply delete these additional properties.
This is horrible JavaScript. If the JS you're importing doesn't do anything to the global object that is worth keeping around when you remove it (for example changing the DOM), then it shouldn't be writing new variables to the global object at all.
Hopefully you have control over the imported JS, and should encapsulate the code in a self-executing function and ensure that all variable declarations start with var
. This means you're not polluting the global object with your own variables and you can do whatever you need to in the script. Your code above would become:
function() {
var globalVar = "some variable";
alert(globalVar);
}();
This will ensure that no new variables are written to the global object, and you still have access to them to change them (which presumably you need to do).
If you want more info, could you shine some more light on what the important script actually does?
精彩评论