Requirejs Introduction (II)

Source: Internet
Author: User
Tags define function script tag

Brief introduction

One of the most commonly used JavaScript libraries today is Requirejs. I've been using Requirejs for every project I've been involved in recently, or I've suggested adding requirejs to them. In this article, I'll describe what Requirejs is, and some of its underlying scenarios.

Asynchronous module definition (AMD)

Talking about Requirejs, you can't get around mentioning what a JavaScript module is, and what AMD is.

The JavaScript module simply follows the code snippet of the SRP (single Responsibility principle sole responsibility principle), exposing a public API. In today's JavaScript development, you can encapsulate many features in a module, and in most projects, each module has its own files. This makes JavaScript developers a bit sad because they need constant attention to the dependencies between modules, loading them in a specific order, or the runtime releasing errors.

When you load a JavaScript module, the script tag is used. In order to load the dependent modules, you must first load the dependent, then load the dependent. When you use the script tag, you need to schedule them to load in this particular order, and the script is loaded synchronously. You can use the async and defer keywords to make the load asynchronous, but you may lose the order of loading during the loading process. Another option is to pack all the script bundles together, but you still need to sort them in the right order when you bundle them.

AMD is such a definition of the module, so that the module and its dependencies can be asynchronously loaded, but in the correct order.

CommonJS, which is a standardized attempt on the generic JavaScript model, contains the AMD definition, and I recommend that you read it before proceeding with this article. In the next version of the JavaScript specification for ECMAScript 6, there are specification definitions for outputs, inputs, and modules, which will become part of the JavaScript language and will not be long. It's also about Requirejs what we want to say.

Requirejs?

Requirejs is a JavaScript file and module framework that can be downloaded from http://requirejs.org/if you use Visual Studio and can also be obtained through NuGet. It supports browsers and server environments such as node. js. With Requirejs, you can sequentially read only the dependent modules that are required.

What Requirejs is doing is loading the dependencies through the Head.appendchild () function when you use the script tag to load your defined dependencies. When dependencies are loaded, Requirejs calculates the order of the module definitions and invokes them in the correct order. This means that all you need to do is use a "root" to read all the features you need, and then just leave the rest to Requirejs. In order to use these functions correctly, all the modules you define need to use the Requirejs API, and no one will work as expected.

The Requirejs API exists under the namespace Requirejs created when Requirejs is loaded. The main API is the following three functions:

    • define– The function user creates the module. Each module has a unique module ID, which is used for Requirejs run-time functions, and the Define function is a global function that does not need to use the Requirejs namespace.
    • require– This function is used to read dependencies. It is also a global function and does not need to use the Requirejs namespace.
    • config– This function is used to configure Requirejs.

In the following, we will teach you to use these functions, but first let's understand the next Requirejs loading process.

Data-main Property

When you download Requirejs, the first thing you need to do is to understand how Requirejs started working. When Requirejs is loaded, it uses the Data-main property to search for a script file (it should be the same script that was loaded with SRC Requirejs). Data-main need to set a root path for all script files. Based on this root path, REQUIREJS will load all the relevant modules. The following script is a use Data-main example:

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

Another way to define the root path is to use the configuration function, which we'll see later. Requirejs Assuming that all dependencies are scripts, you do not need to use the. js suffix when you declare a script to be dependent.

If you want to change the default configuration of Requirejs to use your own configuration, you can use the Require.configh function. The config function needs to pass in an optional parameter object, which includes a number of configuration parameter options. Here are some of the configurations you can use:

    • The baseurl--is used to load the root path of the module.
    • The paths--is used to map a module path that does not exist under the root path.
    • The shims--configuration is outside the script/module and does not use Requirejs's function dependencies and initializes the function. Assuming that underscore does not use the REQUIREJS definition, but you still want to use it through REQUIREJS, you need to define it as a shim in the configuration.
    • deps--Load Dependency Array

Here is an example of using a configuration:

Require.config ({    //by default load any module IDs from Scripts/app    ' Scripts/app ',    //except, if The module ID starts with "Lib"     paths: {        '.. /lib '    },     //the underscore script dependency should be loaded before loading backbone.js deps: [' backb One '      }}});

In this example, the root path is set to Scripts/app, each module that starts with LIB is configured under the Scripts/lib folder, backbone loads a shim dependency.

Defining modules with Requirejs

Modules are objects that are internally implemented to encapsulate, expose interfaces, and reasonably restrict the scope. Reuqirejs provides the Define function for defining the module. As a rule, each JavaScript file should define only one module. The Define function accepts a dependent array and a function that contains a module definition. Usually the module-defined function takes the dependent modules in the preceding array as parameters in order. For example, here is a simple module definition:

define ([function (logger) {                return {             firstName: "John", LastName: "Black", SayHello: function () {logger.log (' hello ');}} });

We see that a module-dependent array containing the logger is passed to the Define function, which is called after the module. Also we see a parameter named Logger in the defined module, which is set to the Logger module. Each module should return its API. In this example we have two properties (FirstName and LastName) and one function (SayHello). Then, as long as the module you define later uses the ID to refer to the module, you can use its exposed API.

Using the Require function

Another very useful function in Requirejs is the Require function. The Require function is used to load module dependencies but does not create a module. For example, the following is a function that uses require to define the ability to use jquery.

Require ([function ($) {    //jquery was loaded and can being used now});  
Summary

In this article I introduced the Requirejs library, which is one of the library functions that I will use to create each JavaScript project. It is not only used to load module dependencies and related commands, Requirejs helps us to write modular JavaScript code, which is very beneficial to the extensibility and reusability of the code.

Requirejs Introduction (II)

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.