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 offunctionAis expecting a return value from that function, there will likely be errors. It is best iffunctionAaccepts a callback that is called whenfunctionAis 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.jsagain.