Use of Requirejs _api (1)

Source: Internet
Author: User

Previously introduced REQUIREJS (modular development), you can look at, but not detailed, so today refer to the official website to introduce in detail:

1. Load JS file:

The goal of Requirejs is to encourage modularity of the code, which uses a script loading step that differs from the traditional <script> tag. It can be used to speed up and optimize code, but its main purpose is to modularize the code. It encourages the use of a module ID instead of a URL address when using a script.

Requirejs loads all the code with an address relative to BaseURL. Page Top <script> label contains a special attribute Data-main,require.js uses it to start the script loading process, while BaseURL is generally set to a directory that is consistent with that property. The settings for BaseURL are shown in the following example:

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

BaseURL can also be set manually via Requirejs config. If you do not explicitly specify config and Data-main, the default baseurl is the directory of the HTML page that contains the Requirejs.

Requirejs default assumes that all dependent resources are JS scripts, so you do not need to add the ". js" suffix to the module ID, Requirejs will automatically append the suffix when parsing the module ID to path. A set of scripts can be set through Paths Config, which helps us to use fewer words when using scripts.

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

Sometimes you want to avoid the "BASEURL + paths" parsing process, but instead directly specify the script that loads a directory. You can do this at this point: If a module ID conforms to one of the following rules, its ID resolution bypasses the regular "BASEURL + paths" configuration, but instead directly loads it into a script relative to the current HTML document:

    • End with ". JS".
    • Start with "/".
    • Contains the URL protocol, such as "http:" or "https:".

In general, it is best to use BaseURL and "Paths" config to set the module ID. It gives you extra flexibility, such as easy script renaming, relocation, and more. At the same time, in order to avoid messy configuration, it is best not to use multi-level nested directory hierarchy to organize the code, but instead of all the scripts are placed in the BaseURL, or divided into a project library/third-party library of a flat structure, as follows:

    • www/
      • Index.html
      • js/
        • app/
          • Sub.js
        • lib/
          • Jquery.js
          • Canvas.js
        • App.js

Index.html:

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

App.js:

requirejs.config ({    // default relative load path    baseUrl: ' Js/lib ',    paths: {        ' .. /app '    }});
Requirejs ([' jquery ', ' canvas ', ' app/sub '),    function   ($, canvas, sub) {         /// function executed after loading succeeded    });
2.data-main entry point:

Require.js will examine the Data-main attribute when loading:

You can set the template load option in the script that Data-main points to, and then load the first application module ... Note: The script you set in Main.js is loaded asynchronously . So if you configure other JS load on the page, there is no guarantee that they depend on the JS has been loaded successfully

3. Define the module:

The module differs from the traditional script file, and it defines a scope well to avoid global namespace contamination. It can explicitly list its dependencies and inject those dependencies in the form of a function (the function that defines the module), without referencing global variables. The Requirejs module is an extension of the module pattern, with the benefit of not having to refer to other modules globally.

Requirejs's module syntax allows it to load multiple modules as quickly as possible, although the order of loading is variable, but the order of dependencies is ultimately correct. And because you don't need to create global variables, you can even load different versions of the same module on the same page.

(If you are familiar with CONMMONJS, see Commonjs's Annotated information for Requirejs module mapping to the COMMONJS module). (----sorry. I have not studied Conmmonjs, look forward to the next study!! )

A disk file should only have 1 modules defined. Multiple modules can be packaged using built-in optimization tools.

(1) Simple value pairs:

If a module contains only value pairs and no dependencies, then the values are defined in define ():

define ({    "black",    "Unisize"});

(2) Functional definition:

If a module does not have any dependencies, but requires a function to do the setup work, define the function in define () and pass it to define ():

// before returning its module definition. Define (function  () {    //do-setupwork-here    return  {        "Black",        "Unisize"    });

(3) There is a functional definition of dependency:

If the module has a dependency: the first parameter is an array of dependent names, and the second argument is a function that is called to define the module after all dependencies of the module have been loaded, so the module should return an object that defines the module. The dependency is injected into the function as a parameter, and the argument list corresponds to the dependent name list one by one.

See Example: (Define a module in Shirt.js, where Cart.js and Inventory.js are in the same directory as it)

function (Cart, Inventory) {        //return an object to define the "My/shirt" module.        return {            "blue",            "large",            function() {                Inventory.decrement (this);                Cart.add (this);}}    );

The module function uses the parameters "cart" and "inventory" to use both of the modules specified with the name "./cart" and "./inventory". The module function is not called until the two modules have been loaded.

Modules are severely discouraged from defining global variables. Following the definition pattern here, you can make different versions of the same module coexist on the same page (see Advanced usage) (but I didn't see it, yet.) "Advanced usage", take a look at it for a moment. )。 In addition, the order of the parameters should be consistent with the dependency order.

The returned object defines the "My/shirt" module. In this definition mode, "My/shirt" does not exist as a global variable.

(4) Define the module as a function:

The return value type of the module is not mandatory to be an object, and the return value of any function is allowed. Here is a module definition that returns a function:

//A module definition inside foo/title.js. It uses//My/cart and My/inventory modules from before,//But since foo/title.js are in a different directory than//The "My" modules, it uses the "my" in the module dependency//name to find them. The "my" part of the name can be mapped//To all directory, but by default, it's assumed to BES a//sibling to the "foo" directory.

Define (["My/cart", "My/inventory"], function(Cart, inventory) {//return a function to define "Foo/title". //It Gets or sets the window title. return function(title) {returnTitle? (Window.title =title): Inventory.storename+ ' +Cart.name; } });

(5) Simple packaging Commonjs to define the module:

If you have existing code that is written in the COMMONJS module format that is difficult to refactor using the above dependency name array parameter, you might consider directly mapping these dependencies to some local variables. You can use a commonjs simple wrapper to achieve:

Define (function(require, exports, module) {        var a = require (' A '),            = Require (' B ');         // Return The module value        return function  () {};    });

The wrapping method relies on Function.prototype.toString () to assign the function content to a meaningful string value, but it does not work in some devices such as PS3 and some old opera mobile browsers. Consider using the optimizer on these devices to export the dependency to an array form.

For more information, see the Commonjs notes page and the "Sugar" section of the Why AMD page.

(6) Define a named module:

You may see that some define () contains a module name as the first parameter:

// explicitly defines the "Foo/title" module:    Define ("Foo/title",        ["My/cart", "My/inventory"],        function(CART, Inventory ) {            //Define Foo/title object in here.        }    );

These are often generated by the optimization tool. You can also explicitly specify the module name yourself, but this makes the module less portable-that is, if you move the file to a different directory, you have to rename it. It is generally better to avoid hard coding of the modules, but to give the optimizer tools to generate them. The optimization tool needs to generate the module name to make multiple modules into a single package, speeding up to the browser's manned speed.

(7) Precautions:

① a file a module:

Each JavaScript file should define only one module, which is the natural requirement of the module name-to-file name lookup mechanism. Multiple modules are optimized for optimization tools, but you should place multiple modules in one file when using the Optimization tool.

the relative module name in define ():

in order to be able to use calls such as require ("./relative/name") inside define () to correctly resolve relative names, remember to inject "require" itself as a dependency into the module:

function (Require) {    var mod = require ("./relative/name");});

Or, better yet, use the shorter syntax set for the conversion COMMONJS module as follows:

Define (function(require) {    var mod = require ("./relative/name");});

Relative paths are especially useful in scenarios where you create modules in a directory to facilitate the sharing of code with other people or projects. You can access the module's neighboring modules without knowing the name of the directory .

generates a URL address relative to the module:

You may need to generate a URL address relative to the module. You can inject "require" as a dependency and then call Require.tourl () to generate the URL:

function (Require) {    var cssurl = Require.tourl ("./style.css");});

Console debug:

If you need to handle a loaded module that has been called through require (["module/name"], function () {}), you can get it using the module name as a require () call to the string parameter:

Require ("Module/name"). Callsomefunction ()

Note that this form only works if "Module/name" has been loaded by the Require (["module/name"]) of its asynchronous form. Relative paths of the form "./module/name" can only be used inside define.

(8) Cyclic dependence:

Jsonp is a way of service invocation in JavaScript. It simply initiates an HTTP GET request through a script tag, which is a recognized means of implementing cross-domain service invocation.

In order to use the JSON service in Requirejs, you need to specify the value of the callback parameter as "define". This means that you can consider the value of the obtained JSONP URL as a module definition.

The following is an example of a call to the JSONP API endpoint. In this example, JSONP's callback parameter is "callback", so "Callback=define" tells the API to wrap the JSON response into a "define ()":

Require (["Http://example.com/api/data.json?callback=define"],    function  (data) {         //The data object would be is theAPI responsefor the        //JSONP data call.         console.log (data);    });

This usage of JSONP should be limited to the initialization of the application. Once the JSONP service times out, other modules defined through define () may not be executed, and error handling is not very robust.

only JSONP services that return a value type JSON object are supported , and other return types such as arrays, strings, numbers, etc. are not supported.

This feature should not be used for JSONP connections to long-polling classes-APIs that handle real-time streaming. These APIs usually do a script cleanup after receiving a response, while Requirejs can only get the JSONP URL once--the subsequent use of require () or define () to initiate a dependency on the same URL (request) will only get a cached value.

JSONP invocation errors typically occur in the form of a service timeout because simply loading a script tag typically does not get a very detailed network error message. You can override Requirejs.onerror () to get past the error. See the error Handling section for more information.

(9) undefining a Module:

There is a global function requirejs.undef () used to undefine a module. It resets the internal state of the loader so that it forgets a previously defined module.

However, if other modules have used this module as a dependency, the module will not be cleared, so this function is only used in error handling when no other module holds the module, or when the module needs to be loaded in the future. See Example of a errbacks segment.

Semi-private Onresourceload APIs may be useful if you plan to do some complex dependency graph analysis at undefine.

Use of Requirejs _api (1)

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.