Understanding the modular loading of JavaScript with Requirejs

Source: Internet
Author: User
Tags jquery library

This is I saw a piece about Requirejs beginner's article, writes well, below unifies own understanding to record:

Original: http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/

Modular programming is used to break large applications into smaller blocks of manageable code. Module based coding eases the effort for maintenance and increases reusability. However, managing dependencies between modules is a major concern developers face throughout the application development P Rocess. Requirejs is one of the most popular frameworks around for managing dependencies between modules. This tutorial examines the need for modularized code, and shows how to Requirejs can help.

Loading JavaScript Files

Large applications often require a number of JavaScript files. Generally, they is loaded one by one using <script> tags. Additionally, each file can potentially is dependent on the other files. The most common example would is jquery plugins, which is all dependent upon the core JQuery library. Therefore, JQuery must is loaded before any of its plugins. Let's look at a simple example of the JavaScript file loading in real applications. Assume we have the following three JavaScript files.

purchase.js

function Purchaseproduct () {  console.log ("function:purchaseproduct");   var credits = Getcredits ();  if (Credits > 0) {    reserveproduct ();    return true;  }  return false;}

  products.js

function Reserveproduct () {  console.log ("function:reserveproduct");   return true;}

  credits.js

function Getcredits () {  console.log ("function:getcredits");   var = "Credits";  return credits;}

In this example, we is trying to purchase a product. First, it checks whether enough credits is available to purchase the product. Then, upon credit validation, it reserves the product. Another script, main.js initializes the code purchaseProduct() by calling, as shown below.

var result = Purchaseproduct ();

  

What Can Go wrong?

In this example, purchase.js depends upon both credits.js and products.js . Therefore, those files need to be loaded before calling purchaseProduct() . So, what would happen if we included our JavaScript files in the following order?

<script src= "Products.js" ></script><script src= "purchase.js" ></script><script src= " Main.js "></script><script src=" Credits.js "></script>

Here, initialization is the done before is credits.js loaded. This would result in the error shown below. And this example only requires three JavaScript files. In a much larger project, the things can easily get out of control. That's where Requirejs comes into the picture.

Introduction to Requirejs

Requirejs is a well known JavaScript module and file loader which are supported in the latest versions of popular browsers. In Requirejs we separate code to modules which each handle a single responsibility. Additionally, dependencies need to being configured when loading files. Let's get started by Downloadingrequirejs. Once downloaded, copy the file to your project folder. Let's assume our project's directory structure now resembles the following image.

All the JavaScript files, including the Requirejs file, is located inside the scripts folder. The file main.js is used for initialization, and the other files contain application logic. Let's see how the scripts is included inside the HTML file.

<script data-main= "Scripts/main" src= "Scripts/require.js" ></script>

The only code required to include files using Requirejs. You might is wondering what happened to the other files and how they is included. The data-main attribute defines the initialization point of the application. It is main.js . Requirejs uses to look for other main.js scripts and dependencies. The scenario all files is located in same folder. Using logic, you can move the files to any folder prefer. Now let's take a look at main.js .

Require (["Purchase"],function (purchase) {  purchase.purchaseproduct ();});

  

In Requirejs, all code was wrapped in require() or define() functions. The first parameter of these functions specifies dependencies. In the previous example, initialization are dependent on purchase.js , since it defines purchaseProduct() . Note that the file extension has been omitted. This was because Requirejs only considers .js files.

The second parameter to be an require() anonymous function which takes a object that's used to call the functions inside the Dependent file. In this scenario, we have just one dependency. Multiple dependencies can be loaded using the following syntax.

Require (["A", "B", "C"],function (A,b,c) {});

  

Creating Applications with Requirejs

In this section we is going to convert the plain JavaScript example discussed in the previous sections into Requirejs. We already covered main.js , so let's move on to the other files.

purchase.js

Define (["Credits", "products"], function (credits,products) {   console.log ("function:purchaseproduct");   return {    purchaseproduct:function () {       var = credits.getcredits ();      if (Credit > 0) {        products.reserveproduct ();        return true;      }      return false;}}  );

  

First, we declare that purchase functionality depends on the credits and products. Inside return The statement, we can define the functions of each module. Here, we had called getCredits() the and reserveProduct() functions on the objects passed. product.js credits.js and is similar, and is shown below.

products.js

Define (function (products) {  return {    reserveproduct:function () {      Console.log ("Function:reserveproduct ");       return true;}}  );

  credits.js

Define (function () {  console.log ("function:getcredits");   return {    getcredits:function () {      var credits = "+";      return credits;}}  );

  

Both of these files are configured as independent modules–meaning they is not dependent on anything. The important thing to notice are the use of define() instead of require() . Choosing between require() or define() depends on the structure of your code, and would be discussed in the following section.

Using require()Vs. define()

Earlier I mentioned that we can use the both and to require() define() load dependencies. Understanding the difference between those and functions is essential to managing dependencies. require()The function is used-to-run immediate functionalities, while was used to define modules for use in define() multiple loc Ations. In our example we need to run the purchaseProduct() function immediately. So, was require() used inside main.js . However, the other files is reusable modules and therefore use define() .

Why Requirejs is Important

In the plain JavaScript example, an error is generated due to the incorrect order of file loading. Now, delete the file in the Requirejs example and see how credits.js it works. The following image shows the output of the browser inspection tool.

The difference is, and no code has been executed in the Requirejs example. We can confirm it since nothing are printed on the console. In the plain JavaScript example we had some output printed on the console before generating the error. Requirejs waits until all the dependent modules is loaded before executing the functionality. If any modules is missing, it doesn ' t execute any code. This helps us maintain the consistency of our data.

Managing the Order of Dependent Files

Requirejs uses asynchronous Module Loading (AMD) for Loading files. Each dependent module would start loading through asynchronous requests in the given order. Even though the file order is considered, we cannot guarantee the first file are loaded before the second file due to The asynchronous nature. So, Requirejs allows us-to-use the shim config to define the sequence of files which need to being loaded in correct order. Let's see how we can create the configuration options in Requirejs.

Requirejs.config ({  shim: {    ' source1 ': [' dependency1 ', ' dependency2 '],    ' source2 ': [' Source1 ']  }});

Requirejs allows us to provide configuration options using the config() function. It accepts a parameter called shim which we can use to define the mandatory sequences of dependencies. You can find the complete configuration guide in the Requirejs API documentation.

Define (["Dependency1", "Dependency2", "Source1", "source2"], function () {);

Under normal circumstances these four files would start loading in the given order. Here, source2 depends on source1 . So, once have source1 finished loading, would think that all the source2 dependencies is loaded. However, and May dependency1 dependency2 still is loading. Using The shim config, it's mandatory to load the dependencies before source1 . Hence, errors won't be generated.

Conclusion

I Hope this tutorial helps the get started with Requirejs. Although it seems simple, it's really powerful in managing dependencies in large scale JavaScript applications. This tutorial alone isn't enough to cover all the aspects of Requirejs, so I hope you learn all the advanced Configuratio NS and techniques using the official website.

And if you enjoyed reading this post, you'll love learnable; The place to learn fresh skills and techniques from the Masters. Members get instant access to all of SitePoint ' s ebooks and interactive online courses, Likesimply JavaScript.

Comments on this article is closed. Has a question about JavaScript? Why isn't ask it on our forums?

Understanding the modular loading of JavaScript with Requirejs

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.