The use of Require.js

Source: Internet
Author: User

First, why use Require.js?

At the earliest, all JavaScript code was written in a single file, as long as the file was loaded. Later, the code more and more, a file is not enough, must be divided into multiple files, loaded sequentially. The following page code, I believe many people have seen.

<script src= "1.js" ></script>
<script src= "2.js" ></script>
<script src= "3.js" ></script>
<script src= "4.js" ></script>
<script src= "5.js" ></script>
<script src= "6.js" ></script>

This code loads multiple JS files in turn.

This kind of writing has a lot of shortcomings. First of all, when loading, the browser stops the page rendering, the more files loaded, the longer the Web page loses response time, and secondly, because of the existence of a dependency between JS files, Therefore, the load order must be strictly guaranteed (for example, 1.js above 2.js), the most dependent module must be put to the last load, when the dependency is very complex, code writing and maintenance will become difficult.

The birth of require.js is to solve these two problems:

  

(1) To realize the asynchronous loading of JS file, to avoid web page loss response;

(2) The dependency between the management module, easy to write and maintain the code.

Second, the loading of require.js

The first step in using Require.js is to go to the official website to download the latest version first.

After downloading, assume that it is placed under the JS subdirectory, it can be loaded.

<script src= "Js/require.js" ></script>

One might think that loading this file could also cause the webpage to lose its response. There are two solutions, one is to put it on the bottom of the page to load, the other is written as follows:

<script src= "js/require.js" defer async= "true" ></script>

The async attribute indicates that the file needs to be loaded asynchronously to prevent the webpage from losing its response. IE does not support this property, only support defer, so put defer also write on.

After loading require.js, the next step will be to load our own code. Suppose our own code file is Main.js, also placed under the JS directory. Well, just write the following:

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

The purpose of the Data-main property is to specify the main module of the Web program. In the example above, is the JS directory below the main.js, this file will be the first to be loaded require.js. Since the require.js default file suffix is JS, main.js can be shortened to main.

Three, the main module of the wording

In the previous section of the main.js, I called it the "main module", meaning the entry code for the entire page. It's kind of like the C-language main () function, where all the code starts running.

See below, how to write Main.js.

If our code does not depend on any other modules, then you can write the JavaScript code directly.

Main.js

Alert ("Loaded successfully! ");

But in this case, there is no need to use the require.js. The real common scenario is that the main module relies on other modules, and the Require () function defined by the AMD specification is used.

Main.js

Require ([' Modulea ', ' Moduleb ', ' Modulec '], function (Modulea, Moduleb, Modulec) {

Some code here

});

The Require () function accepts two parameters. The first parameter is an array that represents the dependent module, the example above is [' Modulea ', ' Moduleb ', ' modulec ', i.e. the main module relies on these three modules; The second parameter is a callback function, which is called when the module specified by the current polygon is loaded successfully. The loaded module passes in the function as a parameter, allowing the modules to be used inside the callback function.

Require () asynchronously loads Modulea,moduleb and Modulec, the browser does not lose its response; it specifies a callback function that only the preceding modules will run after they are successfully loaded, resolving the dependency problem.

Below, let's look at a practical example.

Assuming that the main module relies on the three modules of jquery, underscore, and backbone, Main.js can write this:

Require ([' jquery ', ' underscore ', ' backbone '), function ($, _, backbone) {

Some code here

});

Require.js will load jquery, underscore, and backbone before running the callback function. The code for the main module is written in the callback function.

Iv. Loading of modules

In the last example of the previous section, the dependency module of the main module is [' jquery ', ' underscore ', ' backbone ']. By default, Require.js assumes that the three modules are in the same directory as Main.js, with filenames jquery.js,underscore.js and backbone.js, and then loaded automatically.

Using the Require.config () method, we can customize the load behavior of the module. Require.config () is written on the head of the main module (main.js). A parameter is an object that specifies the load path for each module by the paths property of the object.

Require.config ({

Paths: {

"jquery": "Jquery.min",
"Underscore": "Underscore.min",
"Backbone": "Backbone.min"

}

});

The above code gives the file name of three modules, and the path defaults to main.js in the same directory (JS subdirectory). If these modules are in a different directory, such as the Js/lib directory, there are two ways to do it. One is to specify the path individually.

Require.config ({

Paths: {

"jquery": "Lib/jquery.min",
"Underscore": "Lib/underscore.min",
"Backbone": "Lib/backbone.min"

}

});

The other is to directly change the base directory (BASEURL).

Require.config ({

BASEURL: "Js/lib",

Paths: {

"jquery": "Jquery.min",
"Underscore": "Underscore.min",
"Backbone": "Backbone.min"

}

});

If a module is on a different host, you can also specify its URL directly, for example:

Require.config ({

Paths: {

"jquery": "Https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"

}

});

Require.js requirements, each module is a separate JS file. In this case, if multiple modules are loaded, the HTTP request will be issued multiple times, which will affect the load speed of the Web page. As a result, Require.js provides an optimization tool that, when the module is deployed, can be used to merge multiple modules into a single file, reducing the number of HTTP requests.

V. How AMD modules are written

Require.js loaded modules, using AMD specifications. In other words, the module must be written in accordance with AMD's requirements.

Specifically, the module must be defined using a specific define () function. If a module does not depend on other modules, it can be directly defined in the Define () function.

Suppose you now have a math.js file that defines a math module. Well, Math.js is going to write this:

Math.js

Define (function () {

var add = function (x, y) {

return x+y;

};

return {

Add:add
};

});

The loading method is as follows:

Main.js

Require ([' math '], function (math) {

Alert (Math.add ());

});

If the module also relies on other modules, then the first parameter of the Define () function must be an array that indicates the dependency of the module.

define ([' mylib '], function (mylib) {

function foo () {

Mylib.dosomething ();

}

return {

Foo:foo

};

});

When the require () function loads the above module, the Mylib.js file is loaded first.

Vi. loading of non-canonical modules

In theory, require.js-loaded modules must be modules defined in accordance with the AMD specification, with the Define () function. But in fact, even though some popular libraries (such as jquery) are already in compliance with the AMD specification, more libraries don't fit. So, is require.js able to load non-canonical modules?

The answer is yes.

Such modules are used to define some of their characteristics before they are loaded with require (), using the Require.config () method.

For example, both underscore and backbone are not written in the AMD specification. If you want to load them, you must first define their characteristics.

Require.config ({

Shim: {

' Underscore ': {
Exports: ' _ '
},

' Backbone ': {
Deps: [' underscore ', ' jquery '],
Exports: ' Backbone '
}

}

});

Require.config () accepts a configuration object that, in addition to the paths property mentioned previously, has a shim property that is specifically designed to configure incompatible modules. Specifically, each module defines (1) The exports value (the output variable name), indicating the name of the external invocation of the module, and (2) An array of deps that indicates the dependency of the module.

For example, the plugin for jquery can be defined like this:

Shim: {

' Jquery.scroll ': {

Deps: [' jquery '],

Exports: ' JQuery.fn.scroll '

}

}

Seven, Require.js plug-in

Require.js also offers a range of plugins for specific functions.

The Domready plugin allows the callback function to run after the page DOM structure has been loaded.

Require ([' domready! '], function (DOC) {

Called Once the DOM is ready

});

The text and image plug-ins allow require.js to load texts and picture files.

Define ([

' Text!review.txt ',

' Image!cat.jpg '

],

function (Review,cat) {

Console.log (review);

Document.body.appendChild (CAT);

}

);

The use of Require.js

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.