Print Shortlink

Managing JavaScript files using RequireJS – II

In the earlier post we created a HTML page that used three js files, jquery-1.8.3-min.js, A.js and B.js. The page had three <script> tags one for each js file. To re-iterate one of the problems with this approach as mentioned in the previous post, The single page applications that are developed today have link to multiple JS files. Changing the order of inclusion of these files lead to several problems. With new releases every now and then, this can lead to maintainence issues. In our example, changing the order of inclusion, ie., A and B followed by jQuery will make your code throw error.

Let’s solve this problem, by bringing in modularity and manage the dependencies using Require JS framework. To start-with, we’ll arrange our JS files as shown below.

The js files are organized in two folders scripts and app. Also notice the require.js and index.html present in the same level. We’ll focus on the js file “dev.js” which is the master configuration file.

The dev.js file will use the RequireJS API and have the dependencies configured as shown below.

requirejs.config({
	baseUrl : "scripts",
	paths : {
		app : "app",
		lib : "lib"
	}
});
require(["lib/jquery-1.8.3.min","app/A","app/B"],function(){
	console.log("Loaded all the JS files");
});

In dev.js, we first define the folder structure and specify the list of files to be loaded in the specific order. The jquery file is loaded followed by A and B js files. After loading the files the callback function is invoked.

The index.html file looks lot more cleaner and has a reference to the dev.js file but using the data-main attribute, as shown below.

<html>
	<head>
		<script data-main="scripts/dev" src="require.js"></script>
	</head>
	<body>
		<h1>Require JS app</h1>
	</body>
</html>

The dependencies are now segregated and can be managed very effectively thanks to RequireJS. If you browse index.html, you will notice that the browser still sends individual requests for every JS file. This is because, we have not optimized our JavaScript code yet. Let’s discuss how we can optimize JavaScript code using RequireJS in our next post.

Leave a Reply


four × 3 =