Getting Started with Require JS

What is Require JS?

With Require JS your website or web application gets a better structure and a much better performance. We’ll tell you how to use the scriptloader.
JavaScript files are usually embedded in the web page using the script element. For smaller projects, this is not a problem at all. However, if the project grows and the complexity increases, you quickly lose track – and the performance also suffers increasingly from unnecessarily loaded script components.

RequireJS is a JavaScript file and module loader that can improve the speed and quality of your code with a modular design. Strict division of the scripts and an optimized loader routine will give you more structure and performance. We’ll tell you how RequireJS works and how to get started with the library.

This is how RequireJS works

RequireJS is a library equipped with an Asynchronous Module Definition (AMD) API, which can load and provide code blocks and their dependencies for your project. This means that you only have to include one file in your document – no matter how many libraries and scripts you need. Loading the required components then takes over RequireJS for you.

For this, RequireJS needs a fixed structure to allow automatic loading of scripts. For our example, we will use an example of an auxiliary script to do a simple DOM manipulation with jQuery. We will use the following structure:

your project

/ scripts
/ libs
/ helper

The project project.html a project.html file in which we want to execute JavaScript. The subfolder “/ scripts” contains all scripts of the project. There we deposit the require.js file and the main.js file, with which we later take control. In the subfolder “/ libs” we store different libraries and in the subfolder “/ helper” various helper scripts, which we will need for execution. In order to be able to use RequireJS, we now integrate the file into our project. The following code line is sufficient for this:

[cc lang=”javascript”][/cc]

With the data-main attribute in the script element, we tell RequireJS which file is needed to control the program logic. In our case, it’s the main.js file. The omission of “.js” in the data-main attribute is by no means an error: By default, RequireJS assumes that all required files have the suffix “.js”.

Development with RequireJS

Within the main.js file we can now load and execute the required libraries and scripts. To do this, we first define the path to the jQuery library in the main.js file. We have the requirejs.config() method.

[cc lang=”javascript”]requirejs.config({ paths: { “jquery”: [ “”, // If the CDN fails, load from this local module instead “lib/jquery” ] } });[/cc]

We pass an array to the method with the paths to the libraries we want to use. Here we define the name of the library, which we can later use to access the library within the program logic. If we use an array, we can define fallback possibilities for it. In our example, we first refer to a content delivery network (CDN) and, in the event of a bad call, specify the path to the local copy of the jQuery library. The require() method now main.js you the ability to access the jQuery library within the main.js file.

[cc lang=”javascript”]require([“jquery”], function($) { // Dein jQuery Code });[/cc]

In our example, we want to outsource the work to a sub-script. To do this, we create the util.js file in the subfolder “/ helper”, a so-called module, which must first be defined for use with RequireJS. We can do that with the define() method, while setting the dependency on jQuery. The method follows the following pattern:

[cc lang=”javascript”]define( moduleName, // optional, defaults to name of file dependencies, // optional array listing this file’s dependencies function(params) { // Function to execute once dependencies have been loaded // params contains return values from the dependencies } );[/cc]

In our example, the definition of the module could be as follows:

[cc lang=”javascript”]define([“jquery”], function($) { $(‘body’).append(”
Dynamic content on util.js
“); } );[/cc]

Now, to load the util.js file, we return to the main.js file and use the require() method to main.js the just-defined module.

[cc lang=”javascript”]require([“helper/util”]);[/cc]

With the above code we load the file util.js from the sub-folder “/helper”. At the same time, RequireJS loads all the libraries and scripts needed to run util.js – in our case that’s the jQuery library.

Basic implementation and performance optimization with RequireJS

Our basic implementation of RequireJS is complete. If we now consider the loading process of our page, we see that first require.js and then the other scripts of the project are loaded – in the order corresponding to the dependencies. On closer inspection, you can see that the additional scripts are only loaded after the DOM event has been triggered. This means that the additionally needed scripts do not unnecessarily delay the rendering process of our site and thus with the help of RequireJS not only a modularization and thus a better overview but also a positive effect on the performance can be achieved. This way, we can ensure that even for larger projects, only the files that are actually required for execution have to be transferred.

Optimize performance with RequireJS

With the technology behind RequireJS your project benefits from a better overview and gets an automatic performance optimization. With the RequireJS Optimizer, you can take even better advantage of this effect in larger projects: the RequireJS Optimizer combines related scripts, minimizes them and further optimizes them for even better performance. The optimizer is then usually used for fine-tuning or refactoring the project with tools such as Grunt.

More information about the RequireJS Optimizer can be found in the documentation of the script loader . Further information and examples can also be found on the official website of RequireJS.

Recent Articles


Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here