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 offunctionA
is expecting a return value from that function, there will likely be errors. It is best iffunctionA
accepts a callback that is called whenfunctionA
is done with its work. - The above code will call
require()
for every call tofunctionA
; however, after the first call, there is no penalty taken to loadfunctionC.js
, it is only loaded once. The first timerequire()
gets called, it will loadfunctionC.js
, but the rest of the time, RequireJS knows it is already loaded, so it will call thefunction(functionC){}
function without requestingfunctionC.js
again.
You can find details about RequireJS and JavaScript modularity here: JavaScript modularity with RequireJS (from spaghetti code to ravioli code)