RequireJS for Effective JavaScript Module Loading

Posted By : Mahima Gautam | 29-Jul-2018

Today the modular programming is frequently used to break huge applications into smaller modules so it can be easily maintained. This type of coding help to ease the efforts of maintenance and increases the reusability.

 

Loading Javascript Files

 

To load these huge applications we require javascript files. They get loaded one by one in a script tag. Each file can be dependent on other files. Most commonly used examples can be jQuery plugins. That's why it should be loaded before any plugins. Following is the example of the javascript file getting loaded in the real applications.

 

Purchase.js

function purchaseProduct(){
  console.log("Function : purchaseProduct");

  var credits = getCredits();
  if(credits > 0){
    reserveProduct();
    return true;
  }
  return false;
}

 

Product.js

function reserveProduct(){
  console.log("Function : reserveProduct");

  return true;
}

 

Credit.js

function getCredits(){
  console.log("Function : getCredits");

  var credits = "100";
  return credits;
}

 

In the above example, we tried the to purchase a product. Firstly, we checked that there are enough credits that are available for purchasing the product. Then after checking the credit validation, it reserved product. Another script is main.js, that helps to initialize the code by calling the purchaseProduct() function that is below

 

var result = purchaseProduct();

What Can Go Wrong

 

In the first example, Purchase.js was dependent on both credit.js and product.js. However, these files need to be loaded before calling purchaseProduct(). 

 

Introduction to RequireJS

 

Requirejs is a javascript module and file loader that is supported mostly by the latest browser. In this, we divide the code into modules in which each module handle single responsibility. Javascript files, including requireJS are placed inside the scripts folder. Main.js contain initialization and different files have application logic.

 

Using require() vs define()

We can use require() and define() for loading dependencies. The difference between these two are require() function used to run immediate functionalities and define() function is used for defining modules at different locations

 

Why RequireJS is Important

In simple JS example, the error gets generated because of the incorrect order of the file loading. If we delete the credits.js in the above example of requireJS the error will come on console showing no code has been executed. RequireJS sees that all the modules have been loaded or not before executing the functionality. 

 

 

About Author

Author Image
Mahima Gautam

Mahima has a good knowledge of HTML and CSS. She is working as a UI Developer and she loves to dance in her free time.

Request for Proposal

Name is required

Comment is required

Sending message..