4

Is it possible to unload JavaScript with out a page reload?

It's easy to add a file dynamically by ajaxing a file in and appending it to the DOM.

But what about the opposite.

Is there a way to unload a file?

My understanding is that if I append a script element, the JS is loaded. However if I dynamically remove the script element, the JS remains loaded.

Is there a way to unload a JS file.

Here is an example of a dynamic load:

script_el.src = base + 'some_path' + '?_time=' + new Date().getTime();
document.head.appendChild(script_el);
script_el.onload = function () {
    libHasLoaded();
};
6
  • 1
    You could always set the variables within the JS file to null? Commented Jun 24, 2014 at 13:34
  • Why would you want to do that? If you want to disable a running script, you should create a hook within it to allow disable/enable features, not 'unload' the code. Commented Jun 24, 2014 at 13:36
  • I think the answer is ... No. You can not unload JS. If someone wants to mark as an answer with an explanation ... Commented Jun 24, 2014 at 13:48
  • 1
    But you can in theory unload it, it just won't actually stop it from working. (remove the js file from the dom, however that of course doesn't really remove it). The fact is unloading the js file isn't what you want. you want to instead reverse or disable everything that it did. (which IS possible, there just isn't an automated way of doing it.) Commented Jun 24, 2014 at 14:06
  • 2
    You can run a script as a worker in its own thread and terminate it at some point. But removing a script from the interpreter is like removing the salt from a bowl of pea soup. Commented Jun 24, 2014 at 14:20

1 Answer 1

0

There is no automatic way to revert changes made after js loading (if that's what you mean by "unload js"). It is somewhat possible to do that manualy (as in per script) but very very hard indeed. I would not bother doing that. It's better to design your js so that you can disable it by switching some kind of flag.

Sign up to request clarification or add additional context in comments.

Comments