In its most basic form you can use require.js as a script loader over your existing files and have it trigger a callback once done, so loading your app.js + animations.js using require.js works like this:
The anatomy of an AMD module is, most commonly, define(id?, dependencies?, module):
Lets create a small example using two modules + jquery to examine how dependencies work. Jquery, like quite a few popular libraries, registers itself as an AMD module, so I will use it in our examples. This uses three files; index.html, main.js and view.js.
This last module shows how dependency free modules can be written using object literals and thus passing just 1 argument to define.
With this simple example we’ve achieved a few important architectural principles you can use in building out a proper app:
But as we start building code in tiny files we take the penalty of loading that code in chunks.
require.js uses xhr requests in parallel beneath the hood, but since we need to load main.js before we detect the need for jquery + view.js we still get a scenery like this
Now if we were to add 10, 20, 50 more files and they would load in a similar fashion, how would that affect our app? Well, it wouldn’t be pretty! Fortunately for us, require.js is not built for tinker-toys but rather production web sites, and it lets you perform minifying while respecting your modular codes dependencies. You can choose to build one file to rule them all, or several files for every distinct section of your app (this lets you maintain feature dependent loading in an optimised manner).
I’ve set up a grunt.js (a really cool command line js developer tool for automated tasks) config file that will allow you to just run grunt from the projects root to build a compiled version in compiled/main.js.
You also need to change baseUrl setting in index.html for it to load from the compiled folder. In order to install grunt you must have node.js + npm installed and do npm install from the project root.
When minifying your project you have two options; You can either continue loading jquery from a CDN, or you can download it locally and have it concatenated and built into your main.js compiled file. Have a look at the grunt.js file that sets up requirejs compilation and see the two different configs:
After building the project and setting baseUrl: ‘compiled’ we get a better network flow chart:
Thats it! Now we have a simple setup that is ready to be expand and built upon. You can find all source code from this post in this gist, or just git clone git://gist.github.com/4256032.git and continue building!
Where I work (Keyteq Labs, web page in Norwegian) we use require.js in all products and are very satisfied with that. I’m planning to write about some more advanced stuff we do with require.js (+ backbone.js) later on.