Print Shortlink

Managing JavaScript files using RequireJS – I

RequireJS is a JavaScript library that provides two main facilities.

  • Manage dependencies of JavaScript code in our applications
  • Optimize JavaScript code

In this post and subsequent posts we’ll discuss use of RequireJS in our applications. We’ll see how we can manage dependencies and optimize JavaScript code.

Let’s begin with an index.html file that uses jQuery and two other JavaScript files. The body of index.html file is nearly empty. It has a header element with some text in it.

//index.html
<html>
	<head>
		<script src="jquery-1.8.3.min.js"></script>
		<script src="A.js"></script>
		<script src="B.js"></script>		
	</head>
	<body>
		<h1>Require JS example</h1>
	</body>
</html>

index.html refers to three JavaScript files, jquery, A.js and B.js. A.js and B.js have the following code.

//A.js
console.log("*****Loaded A");

var arr = [1,2,3];
$(arr).each(function(index,value){
	console.log(value);
});

//B.js
console.log("*****Loaded B");
$().ready(function(){
	$("h1").css("color","red");
});

As you can see A.js and B.js have very basic code. index.html has link to these three files with jquery being the first one that is included. There’re couple of problems in this approach.

  • 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.
  • When the browser loads index.html you will find from the following picture, that it sends four HTTP requests to the server. The more files you include the more requests to the server. Let’s not forget the fact that we’ve not included CSS and images here.
    . I have named the html file “indexWithoutUsingRequireJS.html” as shown in the picture.

In our next article, we’ll see how we can modularize our JavaScript code using RequireJS framework, so that our application is easier to maintain.

Page 1 of 1

One Response

  1. Managing JavaScript files using RequireJS – II

    […] – II By Prabhu Sunderaraman on December 23, 2012 in JavaScript, RequireJS In the earliest 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 […]

Leave a Reply


× 5 = twenty five