Require.js is a JavaScript module loader, helping to reduce complexity of applications by managing dependencies and allowing easier separation and organisation of code into modules.

Asynchronous Module Definition or AMD modules are a way for applications to manage dependencies and easier separation by organising code into modules. Require.js is one such AMD module loader that can be used with jQuery, node and others, but firstly the JavaScript needs to be refactored appropriately.

Run JSLint over the code

JSLint is a tool that can be run either from the command line, through Gulp or Grunt or even in the browser at, it will highlight issues with the JavaScript to be fixed that will produce better quality code.

Structure the JavaScript

After the issues highlighted by JSLint have been fixed, organise the code so that it follows a more structured outline such as having a collection of vars and functions.


Add the AMD define call

For it to be recognised by module loaders such as require.js, the code needs to be wrapped in define calls which will turn it into an AMD module.


Dependencies such as jQuery

To add any dependencies such as jQuery, simply include them in the define call array such as this:-


Any dependencies added in this way also need to be AMD compatible modules or a shim might be needed, documentation for jQuery can be found here:-

Add a little Encapsulation

One of the advantages of the module pattern is that it can be structured so that variables and functions can be internalised and effectively defined in a 'private' scope. The module's return object can define exactly what should be publicly accessible. In the previous code snippet, the variable foo and both functions were all returned by the module. This means that they would all be publicly accessible by any client code. Instead, we want to ensure that foo and the functions are initially defined as private, and then expose the functions explicitly in the return object.


Happy coding