代码之家  ›  专栏  ›  技术社区  ›  João Pimentel Ferreira

模块和子模块文件完全异步加载

  •  0
  • João Pimentel Ferreira  · 技术社区  · 7 年前

    我希望有一个完全异步的方法来在客户端加载模块的文件,而不需要额外的工具,如RequireJS。我的模块模板遵循 "Revealing module pattern" template .

    在我的档案里 root.js 我有

    root = (function(thisModule){
    
      //I'm stuck here, I know I need to add the already 
      //existent properties of thisModule into here 
      //when child.js is loaded first
    
      function A(){...}
      function B(){...} //public method
    
      return{
         B:B
      };
    
    })(root || {});
    

    在我的文件中 child.js 我有

    root = root || {};
    root.child = (function(){
    
      function C(){...}     
      function D(){...}  //public methods
    
      return{
         D:D
      };
    
    })();
    

    如何重写中的第一个模块 Ro.js 使文件的加载顺序无关 ?也就是说,以下代码永远不会引发异常。

    $.when($.getScript("root.js"), $.getScript("child.js")).done(function(){
       root.B;
       root.child.D;
    });
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   CertainPerformance    7 年前

    对代码的最简单的调整是保留 thisModule -只分配给 B 的属性 该模块 然后返回 该模块 而不是只返回 { B:B } :

    var root = (function(thisModule){
      function A(){ }
      function B(){ } //public method
      thisModule.B = B;
      return thisModule;
    })(root || {});
    

    如果 root 是全局的,如果你明确地提到 window.root 否则,如果不小心将该代码段放在顶层以外的其他位置,则可能会遇到错误:

    window.root = (function(thisModule){ ...
    

    作为补充说明,假设您的构建过程使用babel(任何严肃的项目都应该使用babel),您可以考虑使用速记属性来减少语法干扰,例如:

    return{ D };
    

    而不是

    return{ D: D };
    

    如果方法名没有长语法干扰,这将很有帮助。