【问题标题】:Modules and submodules files fully asynchronous loading模块和子模块文件完全异步加载
【发布时间】:2018-11-25 01:18:51
【问题描述】:

我希望有一个完全异步的方法来在客户端加载模块的文件,而不需要额外的工具,例如 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
  };

})();

如何重写root.js 中的第一个模块使文件的加载顺序无关紧要?也就是说,下面的代码永远不会抛出异常。

$.when($.getScript("root.js"), $.getScript("child.js")).done(function(){
   root.B;
   root.child.D;
});

【问题讨论】:

  • 所以你希望在两个脚本都加载后能够访问root.Broot.child.D,是吗?
  • 我认为 Promise 是这里的必经之路。但你说你不想那样做。在看到加载之前,您是否同意轮询的想法?为什么反对承诺?
  • @mccambridge 你的意思是getScript 中的承诺吗?我希望文件的加载完全异步。
  • @CertainPerformance,是的,并且独立于文件加载顺序。有可能吗?
  • @CertainPerformance 我的问题是当child.js 首先加载时,root.child 会被root.js 的加载删除

标签: jquery performance asynchronous module getscript


【解决方案1】:

对代码最简单的调整是保留 thisModule 的内容 - 只需分配给 thisModuleB 属性,然后返回 thisModule 而不是只返回 { B:B }

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

如果root 是全局的,那么如果你明确引用window.root 可能会更清楚一点,否则如果你不小心把sn-p 放在顶层以外的地方,你可能会遇到错误:

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

附带说明,假设您的构建过程使用 Babel(任何严肃的项目都应该这样做),您可以考虑使用速记属性来减少语法噪音,例如:

return{ D };

而不是

return{ D: D };

如果方法名称很长,这可能会有所帮助 - 减少语法噪音。

【讨论】:

  • 非常感谢,真的!我的项目使用uglify-js压缩js代码。
  • 我重写了我的问题以澄清我的观点,我希望你没问题。无论如何,您已经给出了解决方案。
猜你喜欢
  • 2013-08-28
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
相关资源
最近更新 更多