Load our JavaScript files in the right way with Require.js


Load our JavaScript files in the right way with Require.js

Working on big JavaScript web apps is the nowadays trend. With the latest technologies released in the web development world we can create everything we need, from a simple website to a full real interactive videogame, and the use of massive JavaScript code on client side, but also on server side (Node.js), is a standard practice.

For this reason it is a good idea to organize the structure of your code as cleanly as possible: talking about loading and managing JavaScript code I think that a masterpiece in this field is Require.js, a simple but powerful JavaScript file and module loader powered by AMD API, Asynchronous Module Definition. For more infos about the project, here you can find the official page.

What's the role of Require.js in your project? In simple word, it manages the loading of JavaScript files and modules considering their dependencies, keeping your code structure more clean as possibile and the whole loading time faster. You can forget about things like this:

<script type="text/javascript" src="script-00.js"></script>  
<script type="text/javascript" src="script-01.js"></script>  
<script type="text/javascript" src="script-02-with-deps-00.js"></script>  
.
.
.
.
<script type="text/javascript" src="script-98-with-01-deps.js"></script>  
<script type="text/javascript" src="script-99-with-78-deps.js"></script>  

Really good, right? I think HELL YES: stop unreadable and not maintainable-friendly code, say "hello" to clean and simple structures.


How it works?

The first thing to do is including the only JavaScript file that we will add directly to our DOM.

<script src='path/to/require.js' data-main='assets/js/app'></script>  

This is just a simple call to a script file, but if you check better you can see a data-main attribute: this data show where is placed the main JavaScript file of our application, in our case in the folder "assets/js" named as app.js

After this initial configuration, we can start to code our application. In the main file we have to call the libraries we will use in our project and declaring their dependencies using the method require.config():

// app.js

// configuration
require.config({  
    baseUrl: 'assets/js',
    paths: {
        "jquery": 'libs/jquery.min',
        "TweenMax": 'libs/tweenmax.min',
        "purl": 'libs/purl',
    },   
    shim: {
        "purl" : {
            deps : ["jquery"]
        },
    }
});


// running app
require([  
    'jquery',
    'TweenMax',
    'purl'
     ], function($){

        console.log("Hello World!");

});

Let's comment some code:

  • require.config() is the method used to define the main libraries of our project.
  • baseUrl defines the place where our libraries are placed.
  • paths defines, for every element inside it, the name that will be used inside our app and the path of it.
  • shim defines the dependencies or our libraries, in our case Purl will be loaded after jQuery is fully loaded.
  • require([]) define a part of code that to run correctly need some of libraries defined inside []. In simple words, it starts when our libraries are ready.

In our case, when jQuery, TweenMax and Purl will be ready, we will print "Hello World!" in console.

Last thing to consider is the defining of re-usable modules with their own dependencies. An example of code could be:

// Main JavaScript file
require(["Cars"], function(Cars) {  
    console.log("Car module is ready");
});


// Module "Car" (saved in its own file)
define(["Wheel", "Engine", "Body"], function(){  
    return this;
});

In this example we load Car module in the main.js file, but Car need some other elements defined in its own module file. We are saying "Dude, load Car module", and require.js replies with "Of course man, I load it but I load before its dependencies".
The big different is the rule: define() is used to define re-usable module for our app, require() to simply call a dependency.

Using this system you can write clean code, re-usable modules and manage in simple way their dependencies..

I link here a GitHub repository with a basic example of use, also useful as template.

Hope this post could be helpful, for every question or integration, drop a comment! Cheers!



Daniele Petrarolo

Daniele Petrarolo

http://www.danielepetrarolo.com

In love with #JavaScript, #PHP and #Python / Web Developer / There's no place like 127.0.0.1.

View Comments