This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).
Why RequireJS We are building apps, not web sites Code complexity grows as the app gets bigger We need some sort of #include/import/require #include/import/require #include/import/require #include/import/require ability to load nested dependencies nested dependencies nested dependencies nested dependencies ability to load nested dependencies nested dependencies nested dependencies nested dependencies
Why RequireJS RequireJS is a JavaScript file and module loader JavaScript file and module loader JavaScript file and module loader JavaScript file and module loader Using a modular script loader like RequireJS will improve the speed and quality of your code RequireJS allows modules to be loaded as fast as possible, even out of order, but evaluated in the correct dependency order dependency order Built on the Module Module Module Module Pattern Pattern Pattern Pattern
The Module Pattern A JavaScript code module module module module is some JavaScript code located in registered location located in registered location All of the code that runs inside the function lives in a closure closure closure closure, which provides privacy privacy privacy privacy and state state state state throughout the lifetime of the app
Module Example Technically, it is simply an anonymous function that executes immediately executes immediately (function () { // ... vars and functions defined here are // local to this module // here you can also access global variables }());
Modules VS Script Files A module is different from a traditional script file in that it defines a well well well well- - - -scoped object scoped object scoped object scoped object that avoids that it defines a well well well well- - - -scoped object scoped object scoped object scoped object that avoids polluting the global namespace It can explicitly list its dependencies It can explicitly list its dependencies It can explicitly list its dependencies It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the refer to global objects, but instead receive the dependencies as arguments to the function that defines the module
Using Modules: the Main file Required modules References to Required modules References to required modules This function is called when all dependencies are loaded If a required module calls define(), then this function is not fired until its dependencies have loaded
Module without dependencies public Variables setup code Always Always Always Always one one one one module module module module per file per file per file per file
Wrappers for external libraries Some libraries are not defined as RequireJS modules In this case, you can make a wrapper file to load the needed library