Search code examples
jqueryperformanceasynchronousmodulegetscript

Modules and submodules files fully asynchronous loading


I would like to have a fully asynchronous method for loading modules' files on the client side, without the need of extra tools, such as requireJS. My module template follows the "Revealing module pattern" template.

In my file root.js I have

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 || {});

In my file child.js I have

root = root || {};
root.child = (function(){

  function C(){...}     
  function D(){...}  //public methods

  return{
     D:D
  };

})();

How do I rewrite the first module in root.js such that the files' loading order is irrelevant? That is, the following code will never throw an exception.

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

Solution

  • The simplest tweak to your code would be to preserve the contents of thisModule - just assign to the B property of thisModule and then return thisModule instead of returning only { B:B }:

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

    If root is meant to be global, then it might be a bit clearer if you explicitly refer to window.root, otherwise you might encounter bugs if you accidentally put that snippet somewhere other than at the top level:

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

    As a side note, assuming your build process uses Babel (which any serious project should), you can consider using shorthand properties to reduce syntax noise, eg:

    return{ D };
    

    rather than

    return{ D: D };
    

    which could be helpful if the method names are long - less syntax noise.