In a big web project, we may use various JavaScript files. These JS files may be dependent on other JS files and may be included in a particular order in the page.

For example, all jQuery based libraries must be added after main jQuery file is loaded.

As the project grows in size, it becomes difficult to manage these JS files. Also, if we put multiple JS files at the bottom of the page, they will be loaded one by one and slow down the page.

RequireJS

RequireJS is a JavaScript file and module loader which is supported in most of the latest web browsers.

Using RequireJS has following advantages:

  1. Each modules can be easily separated.
  2. Code is always clear
  3. On the web page, we only have to include single JS file.
  4. Scripts are loaded asynchronously and do not block other independent scripts from loading.

Here is an example of using RequireJS:

Create the following directory structure:

<reqtest>
      index.htm
      app.js
      <js>
          require.js
          <custom>
                 first.js
                 second.js
  1. Download RequireJS from here
  2. In XAMPP or any web server of your choice, create the folder named reqtest (or any name you want)
  3. Paste the require.js file inside the js folder. We will put all external libraries in this folder.
  4. Create two files first.js and second.js inside the custom folder where our own custom files resides.

Add following code to the files:

index.htm

<html>
<head>
    <script src="js/require.js" data-main="app"></script> <!-- app.js will be executed -->
</head>
<body>
    <span id="hello"></span>

    <hr/>

    <input type="button" id="btn" value="Say Hello"/>

    <hr/>

    <span class="a">A1</span> <br/>
    <span class="a">A2</span> <br/>
    <span class="a">A3</span> <br/>
</body>
</html>

app.js

require.config({
    paths: {
        "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min",
        "first" : "js/custom/first",
        "second": "js/custom/second"
    }
});

require(['jquery', 'first', 'second'],function($, first, second){

    $(document).ready(function(){
        first.init();

        second.init();
    });

});

In the above code, we have included jQuery from CDN. We also mentioned the order in which JS files should be included:

jQuery.min.js 
first.js
second.js

first.js

define(function(){

    return{
        init: function(){

            $("#hello").html("Hello World!");

            $("#btn").click(sayHello);
        }
    }
});

function sayHello(){
    alert("Hello there!");
}

second.js

define(function(){

    return{
        init: function(){
            $('.a:even').css('font-weight', 'bold');  /*  :even selects only even elements, index starts with 0 */
        }
    }
});

Now you can run your index.htm file and check the browser’s Network tab to see how the files are loaded.