Require. js getting started (copy)

Source: Internet
Author: User

The recent project used require. js to collect some resources and keep a backup. By the way, I will share it with you.

The following content is transferred fromRuan YifengInstructor's Network Log:

More learning resources:

Require. js Official Website:

A good articleArticle: Http://

1. Why use require. js?

At the earliest time, all JavascriptCodeAll are written in one file. You only need to load this file. Later, there were more and more code, and one file was not enough. It had to be divided into multiple files and loaded in sequence. I believe many people have seen the following webpage code.

<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 sequence.

This writing method has many disadvantages. First, when loading, the browser will stop rendering the web page. The more files are loaded, the longer the response time for the web page will be lost. Secondly, due to the dependency between JS files, therefore, the loading sequence must be strictly guaranteed (for example, in the previous example, 1. JS needs to be in 2. JS front), the module with the largest dependency must be placed at the end of the load, when the dependency is very complex, code writing and maintenance will become difficult.

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

(1) asynchronous loading of JS files to prevent webpage response loss;

(2) Management Module dependencies to facilitate code compilation and maintenance.

Ii. Loading of require. js

The first step to use require. JS is to download the latest version from the official website.

After downloading the file, you can load it under the JS subdirectory.

<SCRIPT src = "JS/require. js"> </SCRIPT>

Some may think that loading this file may also cause the webpage to lose response. There are two solutions: one is to load it at the bottom of the web page, and 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 asynchronously loaded to avoid webpage response loss. IE does not support this attribute and only supports defer. Therefore, defer is also supported.

After loading require. JS, the next step is to load our own code. Assume that our own code file is main. JS, which is also placed under the JS directory. You just need to write it as follows:

<SCRIPT src = "JS/require. js"Data-Main = "JS/main"> </SCRIPT>

The data-main attribute specifies the webpageProgram. In the preceding example, the main. js file under the JS directory is first loaded by require. js. Because the default file Suffix of require. JS is JS, You Can abbreviated main. js as main.

Iii. Writing of the main module

In the previous section main. JS, I called it "Main module", which means the portal code of the entire webpage. It is a bit like the main () function in C language, where all code starts to run.

Next let's take a look at how to write main. js.

If our code does not depend on any other module, we can directly write JavaScript code.

// Main. js

Alert ("loaded successfully! ");

In this case, there is no need to use require. js. The common case is that the main module depends on other modules, and then the require () function defined by AMD specifications is used.

// Main. js

Require (['lelea', 'leleb', 'lelec'], function (modulea, moduleb, modulec ){

// Some code here


The require () function accepts two parameters. The first parameter is an array that indicates the dependent modules. In the preceding example, ['lelea', 'leleb', 'lelec'] indicates that the main module depends on these three modules; the second parameter is a callback function. After all the modules specified in the current interface are loaded successfully, it will be called. The loaded module will pass in the function as a parameter, so that these modules can be used within the callback function.

Require () asynchronously loads modulea, moduleb, and modulec, And the browser does not lose the response. The callback function specified by require () runs only after the previous modules are loaded successfully, solved the problem of dependency.

Next, let's look at a real example.

Assuming that the main module depends on jquery, underscore, and backbone, Main. js can write as follows:

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

// Some code here


Require. js loads jquery, underscore, and backbone first, and then runs the callback function. The code of the main module is written in the callback function.

Iv. Module Loading

In the last example in the previous section, the main module's dependency module is ['jquery ', 'underscore', 'backone']. By default, require. js assumes that the three modules are in the same directory as main. js. The file names are jquery. JS, underscore. JS, and backbone. JS, and then load them automatically.

Using the require. config () method, we can customize the loading behavior of the module. Require. config () is written in the header of the main module (main. JS. The parameter is an object. The paths attribute of this object specifies the loading path of each module.

Require. config ({

Paths :{

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



The above Code provides the file names of the three modules. The path is in the same directory (JS subdirectory) as main. js by default ). If these modules are in other directories, such as the JS/lib directory, there are two writing methods. One is to specify paths one by one.

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 another host, you can directly specify its url, for example:

Require. config ({

Paths :{

"Jquery": ""



Require. js requires that each module is a separate JS file. In this way, if multiple modules are loaded, multiple HTTP requests will be sent, which will affect the webpage loading speed. Therefore, require. js provides an optimization tool. After the module is deployed, you can use this tool to merge multiple modules into one file to reduce the number of HTTP requests.

V. AMD module writing

The modules loaded by require. js adopt amd specifications. That is to say, the module must be written according to AMD regulations.

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 there is a math. js file, which defines a math module. Then, math. js should write as follows:

// 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 this module depends on other modules, the first parameter of the define () function must be an array that specifies the dependency of this module.

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

Function Foo (){

Mylib. dosomething ();


Return {

Foo: foo



When the require () function loads the above module, it loads the mylib. js file first.

6. Load nonstandard modules

Theoretically, the modules loaded by require. js must be defined by the define () function according to AMD specifications. But in fact, although some popular function libraries (such as jquery) Comply with AMD specifications, more libraries do not. So can require. js load nonstandard modules?

The answer is yes.

Before such modules are loaded with require (), use the require. config () method to define some of their features.

For example, neither underscore nor backbone libraries are written in amd specifications. To load them, you must first define their features.

Require. config ({

Shim :{

'Underscore ':{
Exports :'_'

'Background ':{
Deps: ['underscore ', 'jquery'],
Exports: 'backone'



Require. config () accepts a configuration object. In addition to the paths attribute mentioned earlier, this object also has a shim attribute, which is used to configure incompatible modules. Specifically, each module must define (1) the exports value (output variable name), indicating the name used for external calls of this module; (2) deps array, indicating the dependency of this module.

For example, jquery plug-ins can be defined as follows:

Shim :{

'Jquery. scroll ':{

Deps: ['jquery '],

Exports: 'jquery. FN. Scroll'



VII. Require. js plug-in

Require. js also provides a series of plug-ins to implement some specific functions.

The domready plug-in allows the callback function to run after the DOM structure of the page is loaded.

Require (['domainready! '], Function (DOC ){

// Called once the Dom is ready


The text and image extensions allow require. js to load text and image 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.

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: 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.