Understanding when and how to use Require.JS

define() should only be used to define a module. For the above example, where a piece of code should be dynamically loaded, using require() is more appropriate:

functionA.js

functionA(){
  require(['functionC'],function(functionC){
    //use funcC in here to call functionC
  });
}

Some notes:

  • require([]) is asynchronous, so if the caller of functionA is expecting a return value from that function, there will likely be errors. It is best if functionA accepts a callback that is called when functionA is done with its work.
  • The above code will call require() for every call to functionA; however, after the first call, there is no penalty taken to load functionC.js, it is only loaded once. The first time require() gets called, it will load functionC.js, but the rest of the time, RequireJS knows it is already loaded, so it will call the function(functionC){} function without requesting functionC.js again.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)