Using RequireJS to manage your JavaScript dependencies

Using RequireJS to manage your JavaScript dependencies

   Leave a comment   
http://bit.ly/1qhj3ob

If you’ve ever worked on a large web application before, you’ll no doubt already be familiar with the problem of managing a large number of JavaScript files, all being needed in different places and at different occassions. This is where RequireJS comes in.

Within your HTML’s you simply have to include the requirejs file which will run itself and a main JS file. Within this main JS file you can manage and declare your libraries, like jQuery, and any other files you’ll need – these will then get loaded when they are required.

In this article we’ll step through the process of getting a small example up and running.

Step 1 – Download RequireJS

You can grab the RequireJS file from their website at a reasonable ~15kb.

Download View Site

Step 2 – Create a Folder Structure

By default, RequireJS recommends having your JS files in a scripts/ directory – though this is not mandatory, we’ll use this format.

index.html
script/
  -- main.js
  -- require.js
  -- libs/
    -- jquery-2.1.1.min.js

Step 3 – Html Content

At this point we’ll just need to create a standard index.html page used to call both RequireJS and our main JS file.

<!DOCTYPE html>
<html>
    <head>
        <title>Example Project</title>
        <script data-main="scripts/main" src="scripts/require.js"></script>
    </head>
    <body>
    </body>
</html>

Step 4 – Main.JS

This is where we can begin working with our JavaScript. To begin with we’ve linked to an external jQuery library using the require.config method. After this we can then include execute some JavaScript which is dependent on jQuery and as such will load jQuery for us first.

require.config({
    baseUrl: 'scripts/lib',
    paths: {
        'jquery': 'jquery-2.1.1.min'
    }
});

require(['jquery'], function(jq) {

    // jQuery Example
    $('body').css({ "background": "brown" });

});

Optional: Check scripts are loading

You can check RequireJS is working by adding a listener to require’s onResourceLoad.

requirejs.onResourceLoad = function (context, map, depArray) {
    var e = document.getElementById('loaded-scripts');
    for (var i in context.config.paths) {
        e.innerHTML = e.innerHTML + context.config.paths[i] + ">br /<";
    }
}


Download Code Example View Code Example


This is only an introductory example to using RequireJS – it can much more but should give you an over view of what’s possible with it.

Have you used RequireJS on a project and found it benefical? Let us know in the comments


Photo by ezu.

Leave a Reply

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