The index.html as shown below has a link to the require.js file and the main script dev.js.
<html> <head> <script data-main="scripts/dev" src="require.js"></script> </head> <body> <h1>Require JS app</h1> </body> </html>
Shown below is the Network section of Chrome browser when index.html file is loaded.
As you can see, there’re are six requests send to the server. The more the number of JS files, we use the more the number of requests to the server will be sent. Let’s see how we can optimize the number of requests sent to the server.
Require JS provides an optimizer called r.js(Yes that’s the name!!!). You can download r.js from http://requirejs.org/docs/release/2.1.2/r.js. You can save r.js in the same place where require.js and index.html are placed. R.js can be run in NodeJS environment from the command line.
In the command line navigate to the scripts folder and run the following command.
node ../r.js -o name=dev out=prod.js baseUrl=.
When you run the above command an optimized JS file prod.js is generated. prod.js contains minified jquery, A and B JS files minified and optimized into one source. You can modify the index.html to use prod.js instead of dev.js as shown below.
<html> <head> <script data-main="scripts/prod" src="require.js"></script> </head> <body> <h1>Require JS app</h1> </body> </html>
The network section when index.html is loaded looks as shown below.
You’ll now notice that the number of requests send to the server has reduced by one half thanks to r.js. r.js can be used to optimize CSS files as well.
The complete code for the three series article can be downloaded from https://github.com/prabhu-durasoft/Managing_JS_Files_With_RequireJS