Understanding When and How to Use Require.JS

I just started working with Require.JS, and I'm a little unclear in the relevant cases in which it should be used, as well as in the correct way to use it in these cases.

This is how I currently have things set with Require.JS. I have two functions: functionA() and functionB() . Both of these functions require an additional functionC() to work properly.

I only want to load the C () function when necessary, i.e. when function A () or functionB () will be called. Therefore, I have the following files:

functionC.js

 functionC(){ //do stuff } 

functionA.js

 functionA(){ define(['functionC'],function(){ //functionC() is loaded because it is listed as a dependency, so we can proceed //do some functionA() stuff }); } 

functionB.js

 functionB(){ define(['functionC'],function(){ //functionC() is loaded because it is listed as a dependency, so we can proceed //do some functionB() stuff }); } 

So, is this configured correctly? And if I end up calling functionsA () and functionB () on the same page, is that extra work being done as they both load the functionsC.js file? If so, is this a problem? And if so, is there a way to set it up so that they first check if the function.js file has been loaded yet, and load it if it hasn't been? Finally, is this a suitable use of Require.JS?

+66
javascript requirejs
Jan 22 '11 at 10:24
source share
2 answers

define() should only be used to define a module. In the above example, where a piece of code should be dynamically loaded, using require() 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 expects a return value from this function, there will most likely be errors. It is better if functionA accepts a callback that is called when functionA is executed with its work.
  • The above code will call require() for every call to functionA ; however, after the first call, there is no penalty for loading functionC.js , it loads only once. The first time you call require() it loads functionC.js , but the rest of the time RequireJS knows that it is already loaded, so it will call function(functionC){} without calling functionC.js again.
+44
Feb 07 '11 at 18:12
source share

Here you can find detailed information about RequireJS and JavaScript modularity : JavaScript modularity with RequireJS (from spaghetti code to ravioli code)

+21
Nov 15 '12 at 8:30
source share



All Articles