RequireJS is a asynchronous module loader for javascript files. Loading javascript files is one of the major factors that slow down a website, requirejs will load the necessary javascript files in the background while your browser loads other things.

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

-requirejs.org

Let's start:

Here is my index.html page. The script tag has two attributes that are needed. data-main  is the path to your javascript file with your functions, this path becomes the root of your modules, it is the entry point to calling all of your scripts. You can name the file whatever you want, but the convention is to name it main. The src is the path to your require.js file.

Index.html:

1
2
3
4
5
6
7
8
9
<html>
<head>
 <title>RequireJS Demo</title>
 <script data-main="../Scripts/main" src="~/Scripts/require.js"></script>
</head>
<body>
 <span id='foo'></span>
</body>
</html>

main.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
require.config({
 baseUrl: "",
 paths: {
   jquery: '/Scripts/jquery-2.1.4.min'
 }
});

require(['jquery'], function ($) {
 $('#foo').html("Hello World");
})

The require.config module will load any other module id from the baseUrl, and the paths sets an alias for all your js files. In my example jquery is an alias to the actual jquery library. This will change the text of #foo span to 'Hello World' notice how we didn't have to explicitly add jquery to our html.

At this point you are probably wondering why do all this, when adding a one line script is really simple. Here is where it gets interesting. We can define our own modules.

Lets edit our previous code:

tasks.js:

1
2
3
4
5
6
7
define(function () {
    return "This is the first module";
})

define('word2', function () {
    return "This is the second module";
})

main.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
require.config({
 baseUrl: "",
 paths: {
 jquery: '/Scripts/jquery-2.1.4.min',
 word1: '/Scripts/tasks',
 word2: '/Scripts/tasks'
 }
});

require(['jquery', 'word1', 'word2'], function ($, word1, word2) {
 $('#foo').html(word1 + " " + word2);
});

Now in tasks.js we have an anonymous method that gets called when we use word1 and a method word2 in our jquery call. In the config part we add a path to the tasks js file to set an alias.

Here is an image of the network traffic.

Network

I highlighted the necessary files. By looking at the forth column we can see that Index calls require.js, and that require.js calls main.js, jquery-2.1.4.min.js and tasks.js.