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:
Index.html:
<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() {
});
Advantages:
RequireJS provides easy and clean way to load and manage dependencies for your Javascript applications.