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();
};
RK-
  • 12,099
  • 23
  • 89
  • 155
  • 1
    You could always set the variables within the JS file to null? – Tim B James Jun 24 '14 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. – Luan Nico Jun 24 '14 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 ... –  Jun 24 '14 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.) – Kevin B Jun 24 '14 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. – kennebec Jun 24 '14 at 14:20
  • @kennebec - I agree, think about event listeners that are set by the script on the DOM. This is kind of a "just making sure" question. If someone answers "no" I can mark it. –  Jun 24 '14 at 15:23

1 Answers1

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.

freakish
  • 54,167
  • 9
  • 132
  • 169