Most Projects Start Like This:
JavaScript files are included as HTML script tags
' <script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script src="init.js"></script>
<script src="app.js"></script>
What's the problem?
JavaScript tags block page rendering
Each file can potentially be dependent on other files
Not Every JavaScript file is needed when the page first loads
No Encapsulation, Namespace pollution
Asynchronous Module Definition
- Modules are encapsulated.
- Create and reuse code from different part of the site.
- Structured, clean codebase.
- Async loading, managed dependencies.
- Lazy load modules (stuff not used by the user yet can be loaded in background when needed on demand).
- Not a technology, but a specification proposal.
2 important concepts
define() vs require()
Define()
Creates a module that can be used by other modules.
define(id?, [dependencies]?, factory)
require()
When you only need to use modules, not create them.
require([dependencies]?, factory)
config
baseUrl
Root path for module lookups.
waitSeconds
Number of seconds before timing out.
paths
Location of the modules or library.
shim
Libraries that don't support AMD, but you need to manage their dependencies.
Recap
define()
require()
config
baseUrl, waitSeconds, paths, shim
Future - ES6 - Modules
Module definition
module [module ID]
export [variable | function]
Module dependency
import {[var | fn ]} from [module ID]