RequireJS Fundamentals

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:

main.js:

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:

main.js:

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.

Bookmark and Share

Leave a Reply

Your email address will not be published. Required fields are marked *