Unload files loaded with getScript?

"Unloading", if it were really possible, wouldn't make much sense here. Let's take a step back and look at why you don't load all the files to begin with:

  • They're another HTTP request and X bytes, if you don't need them, don't get them
  • They have unwanted effects - you don't want what script X does to happen here

Now look at it from the other side, you have loaded them, which means both of the above have already happened, you paid the request cost of getting them and what they've done. Also, what effect they had on the page can't be generically undone. Just by removing a <script> doesn't remove the functions it declared, event handlers it attached, etc.

In short, why are you trying to unload? If it's to remove the effects, well that one's not easy, not in a generic way anyway. If it's to lighten the page...there's no benefit here, you'll actually just incur the cost of removing the element, with no benefit for the client on the JavaScript side of things.


As pointed by Nick Craver it is hard to understand the reason of why you would want to do that.

However if there would be a valid reason to do so. I would put all the code of loaded script in a class. And when i would like to unload this, i would just assign it to null. eg.

//external file:
o1=new Object();
o1.function1=function(){
     //blah blah blah
   };
o1.function2=function(){
     //blah blah blah
   };
o1.var1=1;

//and if when i'll need to get rid of all of this i can just
o1=null;

I think that there are valid reasons to load and unload scripts. I have written a monitoring tool where content is swapped in and out of the center <div> all the time. Each load requires new functions to be attached to the just loaded content. If you (un)load js specific to the (un)loaded content, then the memory footprint stays small. And you can re-use previously defined function names for slightly different responses, while writing generic xhtml.

Assume a <div> with info on a peace of data. The user wants to edit that specific record so the <div> content is replaced by a form with all kinds of behaviors on buttons, checkboxes, etc. The form is subitted and the <div> is replaced with the original content but reflecting the changes. The form is gone and so is the need for any associated behavior.

I.m.h.o. loading in a certain <div> on your page x.htm + x.css + x.js and replacing them when other content and behavior is needed is by far preferrable over re-analyzing the new content and attach all possible responses even if certain nodes or classes are missing in the new content.

Instead of large javascript files, a set of pluggable js modules keeps my code well-organized and the maintenance of ajax behaviors relatively easy. Support for such a scheme in jQuery would be a tremendous help (for me).

Tags:

Jquery