2

I have 2 javascript files that cannot co-exist. If a user click on one button, it loads one js file. If a user clicks another button, it loads the other file. But the last one needs to be unloaded first

Here is generally what I have:

//pseudocode
if user clicks button one
    loadScript(one);
if user clicks button two
    loadScript(two);

//not psuedocode
function loadScript(name)
{
      var javascriptLoc = name + "/config.js";

      //Unload any scripts that were previously loaded by requirejs
      require.undef(); //HELP

      //once config.js is loaded by requirejs...
      require([javascriptLoc], function(util) {

          //do stuff

      });
}

Is there a way to unload one/config.js and load two/config.js instead? Then when a user clicks on "one", it would load one/config.js instead of two/config.js?

Other ways to word the question:

  • what do I do in requirejs when I have exclusive dependancies...

  • how do I deal with conflict resolution in requirejs...

  • how do I reset or unload scripts previously loaded by requirejs...

Katie
  • 45,622
  • 19
  • 93
  • 125
  • ...Am I going to have to use some other method besides RequireJS? :( http://net.tutsplus.com/articles/web-roundups/for-your-script-loading-needs/ – Katie Aug 29 '13 at 21:12
  • Other script loaders can't unload scripts either. :( – Chris Sep 04 '13 at 17:47
  • Focus on getting these script files to co-exist. There are all sorts of ways to sandbox a script file's contents – Adam Rackis Sep 04 '13 at 17:55

1 Answers1

3

Strictly speaking, browsers don't let you unload JavaScript files. If you load a file a.js that says:

var a = 345;

There is no command in JS/HTML that can undo that. (See also here, and here)

You can load a new set of JS commands that negates the effect of the first file, for example:

if (typeof a === "undefined") 
   var a = 34;
else
   a = 34;

This is starting to get complicated though, isn't it? It might be easier to redesign the modules so reloading isn't necessary, for example:

function option1() {
}
function option2() {
}

//if user clicks button 1
currentOption = option1();
//if user clicks button 2
currentOption = option2();
Community
  • 1
  • 1
Chris
  • 5,876
  • 3
  • 43
  • 69