【问题标题】:RequireJS Conditional Loading Module in a synchronous wayRequireJS 条件加载模块以同步方式
【发布时间】:2016-02-14 07:23:11
【问题描述】:

我有一个模块 ModuleABC,它根据标志加载 modulea 或 moduleb,在加载这些模块后,在模块方法上调用 init。

ModuleABC.js
define(['aa'],function(aa){
    var data;
    load = function(){
        if(data.IsAdmin){
            require(['moduleA'],function(modulea){
                modulea.init(data);
            });
        }
        else if
        {
            require(['moduleB'],function(moduleb){
                moduleb.init(data);
            });
        }
    }
    return initialize{
       load();
    }
})

另一个模块需要 ModuleABC,但是当我到达 moduleabc.load() 时,我不会调用我的 modulea 或 moduleb 初始化方法。

Another Module dependent on ModuleABC
require(['ModuleABC'],function(moduleabc){
    moduleabc.load();
    By the time i reach here, i will not have my modulea or moduleb init method called.
    How do I achieve this?
});

【问题讨论】:

  • 为什么不加载您可能需要的所有内容,而只加载您确实需要的 init
  • 这将是低效的。我有条件地加载模块的原因是只加载需要的而不加载不必要的模块。
  • 您是否对单个文件发出 HTTP 请求?
  • 我不这样做。我猜 Requirejs 是在内部做的。
  • 如果它们都捆绑在一起,那么依赖关系只是对该模块的引用。除非简单地要求一个模块运行一堆代码(它不应该),加载一个模块而不初始化不会是一个实质性的惩罚。

标签: javascript requirejs require amd js-amd


【解决方案1】:

听起来load 函数需要是异步的。此外,您的某些 JavaScript 无效,因此我已对其进行更正:

ModuleABC.js

define(['aa'], function (aa) {
    var data;
    function load(cb) {
        var module = data.IsAdmin ? 'moduleA' : 'moduleB';
        require([module], function (module) {
            module.init(data);
            cb();
        });
    }
    return {
       initialise: load
    };
});

AnotherModule.js

require(['ModuleABC'], function (moduleabc) {
    moduleabc.load(function () {
        // By this point, either `moduleA` or `moduleB` will have been loaded and initialised
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多