简体   繁体   English

RequireJS:如何卸载以前加载的javascript文件? 又名排他性依赖关系? 还是重置RequireJS?

[英]RequireJS: How do I unload previously loaded javascript file? Aka Exclusive Dependancies? Or maybe Reset RequireJS?

I have 2 javascript files that cannot co-exist. 我有2个无法共存的javascript文件。 If a user click on one button, it loads one js file. 如果用户单击一个按钮,则将加载一个js文件。 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 ? 有没有办法卸载一个/ config.js和装载两个/ config.js Then when a user clicks on "one", it would load one/config.js instead of two/config.js? 然后,当用户单击“一个”时,它将加载一个/config.js 而不是两个/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... 我该如何处理requirejs中的冲突解决方案 ...

  • how do I reset or unload scripts previously loaded by requirejs... 如何重置或卸载先前由requirejs加载的脚本...

Strictly speaking, browsers don't let you unload JavaScript files. 严格来说,浏览器不允许您卸载JavaScript文件。 If you load a file a.js that says: 如果您加载一个文件a.js,内容为:

var a = 345;

There is no command in JS/HTML that can undo that. JS / HTML中没有命令可以撤消该命令。 (See also here , and here ) (另请参见此处此处

You can load a new set of JS commands that negates the effect of the first file, for example: 您可以加载一组新的JS命令来抵消第一个文件的影响,例如:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM