Modularize your code with RequireJS

Aug 25, 2015


Modular programming is employed to break giant applications into smaller blocks of manageable code. Module based coding eases the effort for maintenance and increases reusability.

RequireJS is a script loader that asynchronously loads your JS to improve page load performance, also provides the ability to organise your JS into self contained modules. Modules are nothing but a JS file and each module is enclosed in a define tag and lists the file dependencies.

Inside each module, you need to declare the dependencies and pass them to your current module. Whenever we have dependency, we have to decouple our JS logic.

If we aren't employing a specific module format, then we want to bear in mind of inner file dependencies once separating logic into completely different files and so transfer them along at build time.

Directory structure:



<script datamain="scripts/main" src="scripts/require.js"></script> 

The datamain attribute defines the data format purpose of the applying. It uses main.js to appear for alternative scripts and dependencies.

In this, the code is wrapped in require() or define() functions. The first parameter of these functions specifies dependencies. The second parameter to require() is an anonymous function which takes an object that is used to call the functions inside the dependent file.

Why we use require() method:

This method only loads what you need, and when you need it.

require(["moduleA "],function(a){

//code logic here//


Why we use define() method:

We Know that, each module is a script, so that a script must declare itself as a module by calling define() and list its dependencies in this corresponding define().

Multiple dependencies order:

define(["dependency1","dependency2","source1","source2"], function() {



  • It allows you to separate your codebase into small reusable pieces.
  • RequireJS will improve the speed and quality of your code.
  • You can create and reuse modules without polluting the global namespace.
  • You can structure your code.
  • You can build for production.

RequireJS provides easy and clean way to load and manage dependencies for your Javascript applications.

You can learn more about RequireJS at

Previously:  Next up: 


News Letter Sign up

Get in touch with us
phone_footer.png  +1 903-306-2430,
              +1 855-978-6816