RequireJS Basics
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).
http://www.di.univaq.it/malavolta
2. Roadmap
• Why RequireJS
• Using modules
• Defining modules
• Wrappers for external libraries
3. 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
ability to load nested dependencies
4. What we want to avoid
uncontrolled scripts
loose control flow
understanding
5. Why RequireJS
RequireJS is a 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
Built on the Module Pattern
6. The Module Pattern
A JavaScript code module is some JavaScript code
located in registered location
All of the code that runs inside the function lives in a
closure,
closure which provides privacy and state
throughout the lifetime of the app
7. Module Example
Technically, it is simply an anonymous function that
executes immediately
(function () {
// ... vars and functions defined here are
// local to this module
// here you can also access global variables
}());
8. Modules VS Script Files
A module is different from a traditional script file in
that it defines a well-scoped object that avoids
well-
polluting the global namespace
It can explicitly list its dependencies and get a
handle on those dependencies without needing to
refer to global objects, but instead receive the
dependencies as arguments to the function that
defines the module
9. Roadmap
• Why RequireJS
• Using modules
• Defining modules
• Wrappers for external libraries
11. Using Modules: the Main file
References to
Required modules
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
12. Roadmap
• Why RequireJS
• Using modules
• Defining modules
• Wrappers for external libraries
15. Roadmap
• Why RequireJS
• Using modules
• Defining modules
• Wrappers for external libraries
16. 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