Require.js's AMD Specification

Source: Internet
Author: User

require.js Introduction to use

In the beginning of the web development of the Wild era, a page only need to load one or a small number of JS files, there is no module, there is no conflict and other problems, but with the development of the Web project, it is more and more large, JS files at every turn dozens of, how to load becomes a problem, to the browser performance considerations, There are also dependencies for each JS file (module). The appearance of require.js is to solve such problems.

1, the implementation of JS file asynchronous loading, to avoid web page loss response.

2, the management module between the dependencies, easy to write code and maintenance.

require.js Loading

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.

<type= "Text/javascript"  src= "Require.js"></ Script >

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:

<type= "Text/javascript"  src= "Require.js"  data-main = "Main.js" ></ 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.

How the main module (main.js) is written

All the code is running from here. 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.jsrequire ([' Modulea ', ' Moduleb ', ' Modulec '], function (Modulea, Moduleb, Modulec) {    //some code here});

The Requier () function accepts two parameters. The first parameter is an array that represents the dependent module, as in the example above [' Modulea ', ' Moduleb ', ' Modulec ']; the second parameter is a callback function, the current polygon module is loaded successfully, and the dependent module is passed in as a parameter. You can then use the method of the dependent module within the callback function.
Require () asynchronously loads the Moudulea,mouduleb,moudulec, the browser does not lose its response, and the callback function specified is not run until the module is loaded, resolving the dependency problem.

An example of the actual point below
Assuming that the main module relies on jquery, and backbone these two modules, Main.js should write like this.

1 require (["jquery", "backbone"],function ($,backbone)2{3    //code 4 })

Require will load jquery and backbone first, and then in the run callback function, the parameter in the callback function is the kana of the function using the dependent module.

Module Loading

In the above example rollup, the main module dependent module is jquery and backbone default case, Require.js jiading these two modules with Main.js in the same directory, the filenames are jquery.js and backbone.js, then you automatically load.

Using the Require.config () method, we can customize the load behavior of the module. Require.config () is written in the header of the main module, and the parameter is an object, and the paths property of the object specifies the load path for each module.

Require.config (    {        path:{            "jquery": "Jquert.min",            "backbone": "Backbone.min"        }        })

If the other modules are not in one path to the main function, and the modules are in the Js/assest directory, they will be written in two ways, one for each path specified.

Require.config ({    path:{        "jquery": "Assest/jquery.min",        "backbone": "Assest/backbone.min"    }    })

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

Require.config ({    baseUrl: "Js/assest",    path:{        "jquery": "Jquert.min",         "backbone": " Backbone.min "    }    })

If you are using a CDN service

Require.config ({     path:{         "jquery": "Https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"     }     })  
How AMD modules are written

Require.js loaded modules, using AMD specifications. So the modules you write must be written in accordance with AMD's rules.
The module must be defined with a specific define () function when it is familiar.
Suppose you now have a math.js file, which is a math module, then math.js should write as follows.

Math.jsdefine (Functio ()    {        var add = function (x, y)        {            return x+y;        };        return{            Add:add        }})  

How this module is used

Require (["Math"],funciton (math) {    consolo.log (Math.add (2,3))    })

If this module also relies on other modules.

Define (["Mylib"],function (mylib) {    function foo () {    mylib.do ();} return{    Foo:foo}})

The Require () function loads the above module and adds it to the Mylib.js file first.

loading modules that are not AMD compliant

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:

Require.config ({    shim:{        jquery.scroll:{            deps:["Jquery"],            exports: ' JQuery.fn.scroll '        }    }    })

Require.js's AMD Specification

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.