JavaScript modular Programming (III): the use of require.js

Source: Internet
Author: User
Tags add define array object config json require return

Today we'll explain how to use them in combat.

I'm using a very popular library require.js.

One, why should use Require.js?

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






This code loads multiple JS files sequentially.

There are a lot of drawbacks to this way of writing. First of all, when loading, the browser will stop the page rendering, the more loading files, the longer the page will lose the response time, and secondly, because the JS file dependencies, Therefore, we must strictly ensure the loading sequence (such as the above example of the 1.js to be in front of 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 files to avoid web page loss of response;

(2) Management of the dependencies between modules, easy to write code and maintenance.

Second, the loading of require.js

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

After downloading, assume that it is placed under the JS subdirectory, you can load.

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

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

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

The function of the Data-main property is to specify the main module of the Web page program. In the above example, is the JS directory below the main.js, this file will be the first to be require.js loaded. Because the require.js default file suffix name is js, you can abbreviate main.js to main.

Third, the main module of the formulation

The main.js in the previous section, which I call the "main module", means the entry code for the entire page. It's kind of like the C language main () function, where all the code starts running.

Here is a look, how to write Main.js.

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

Main.js

Alert ("Load succeeded!") ");

But in this case, there is no need to use 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 argument is an array, represents the dependent module, the example is ["Modulea", "Moduleb", "Modulec"], that is, the main module relies on these three modules; The second parameter is a callback function, which is invoked when the module specified by the current plane is successfully loaded. The loaded modules are passed in as arguments to the function, which can be used inside the callback function.

Require () asynchronously loads Modulea,moduleb and Modulec, the browser does not lose its response, and its specified callback function, which runs only after the previous module has been successfully loaded, solves the dependency problem.

Next, 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.

Four, the module loading

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

Using the Require.config () method, we can customize the loading behavior of the module. Require.config () is written on the head of the main module (main.js). The parameter is an object that specifies the load path of each module in 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, the path defaults to main.js in the same directory (JS subdirectory). If these modules are in other directories, such as the Js/lib directory, there are two ways to do it. One way is to specify the path.

Require.config ({

Paths: {

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

}

});

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

Require.config ({

    BaseURL: "Js/lib",

Paths: {

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

}

});

If a module is on another 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. This way, if you load multiple modules, you emit multiple HTTP requests that affect the speed at which the Web page loads. As a result, Require.js provides an optimization tool that, when deployed, can be used to merge multiple modules into a single file, reducing the number of HTTP requests.

Five, the AMD module's formulation

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

Specifically, the module must be defined with a specific define () function. If a module does not rely 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. So, 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 (1,1));

});

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 non-canonical modules

In theory, Require.js loaded modules must be in accordance with the AMD specification, using the Define () function defined modules. But in fact, although there are already some popular libraries (such as jquery) that conform to AMD specifications, more libraries do not match. So is require.js capable of loading non-standard modules?

The answer is OK.

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

For example, both the underscore and backbone libraries are not written using 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 previously mentioned paths attribute, has a shim property that is specifically configured to configure incompatible modules. Specifically, each module defines (1) The exports value (the output variable name) indicating the name of the module outside the call, and (2) the Deps array, indicating the module's dependencies.

For example, the jquery plug-in can be defined as:

Shim: {

"Jquery.scroll": {

Deps: ["jquery"],

Exports: "JQuery.fn.scroll"

}

}

Seven, Require.js plug-ins

Require.js also offers a range of plug-ins to implement certain features.

The Domready plug-in allows the callback function to run after the page DOM structure has completed loading.

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

Called Once the DOM is ready

});

The text and image plug-ins are allowed to load require.js and picture files.

Define ([

"Text!review.txt",

"Image!cat.jpg"

],

function (Review,cat) {

Console.log (review);

Document.body.appendChild (CAT);

}

);

Similar plug-ins include JSON and Mdown, which are used to load JSON files and markdown files.



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.