Require. js learning Summary

Source: Internet
Author: User

1. Why use require. js as the namespace and namespace;
Load js asynchronously to avoid blocking and improve performance. js loads through require without having to write a lot of script2 and require. js loads require. js. After downloading and downloading it, you can load it in the specified directory.

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

Although this writing method is simple, it is not recommended. The general writing method also needs to add a property:

<script data-main="js/main" src="js/require-jquery.js"></script>  
Just as a c program always has a main method as the entrance, the above writing has done a few things:
1. loaded the require-jquery.js file. Note: The official require. js and jquery package versions are provided and recommended.
2. After loading, load the entry file js/main. js. Note that you do not need a suffix when writing main. js.
All your other js module files can be written in main. js and loaded through main. js. 3. Configure require. js in the master file specified by data-main through require. config and load other js modules.
require.config({    baseUrl: 'js/',    paths: {        "backbone": "backbone",        "underscore": "underscore"    },    shim: {        "backbone": {            deps: [ "underscore" ],            exports: "Backbone"        },        "underscore": {            exports: "_"        }    }});
BaseUrl: Specify the base path paths: module loading path shim: Load non-AMD specification Module
  1. Exports value (name of the output variable) indicates the name used for external calls of this module;
  2. Deps array, indicating the dependency of the module.
  3. The main module can load and add basic project modules and define global methods.
  4. require(['jquery', 'underscore', 'backbone'], function ($, _, Backbone){     // some code here   });
    4. Define the modules loaded by require. js (complying with AMD specifications) and 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     };   });

    Number of returned functions in the defined Module

    1. define has only one return function. The require callback function can directly replace the function name with an alias.

    2. When define return has multiple functions, the require callback function must use an alias to call all functions.

    require(['selector','book'], function(query,book) {    var els = query('.wrapper');    book.fun1();    book.fun2();});
    Here, the query function is 1 and the book function is 2.
    5. Until loading the js file, we have met two keywords: define, which can be used to define the module (namespace). The first part is described. The other is require, other js files can be loaded directly. In addition to simple usage:
    <script>require( ["some" ] );</script>
    In addition, there are complex usage similar to define:
    <Script> require (["aModule", "bModule"], function () {myFunctionA (); // use aModule. myFunctionA myFunctionB () in js; // use bModule. myFunctionB} in js); </script>
    To sum up, define is used when you define your own modules. you can load other js files by the way. require is straightforward for you to load. It is a loading method, aliases can be defined.
    6. requ. 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(['domready!'], 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. 7. Other issues 1. When the path and suffix are in a js file of require, the suffix is generally not required. If the suffix is added, it is loaded according to the absolute path. If there is no suffix name, it is loaded according to the following path:
    <script data-main="js/main" src="js/require-jquery.js"></script>
    That is, the directory specified by data-main is loaded by default, that is, the directory where the js/main. js file is located. Of course, you can modify it in the configuration file.
    2. The define module method can only be used in an independent js file and cannot be used directly on the page.
    Otherwise, the Mismatched anonymous define () module error is reported.

    3. In the code, require a file multiple times does not cause repeated loading by the browser.

    No, this is the advantage of RequrieJS. Even if you repeatedly request it, it is loaded only once.

    8. Go to require. 1. cdn rollback: When CDN loading is incorrect, the local database is loaded. We can achieve this through require. config:
    requirejs.config({    paths: {        jquery: [            '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js',            'lib/jquery'        ]    }});
    2. No dependency? Object literal volume? No problem!
    When you write a module without any dependencies and only return an object containing some function functions, we can use a simple Syntax:
    define({    forceChoke: function() {    },    forceLighting: function() {    },    forceRun: function() {    }    });
    It is very simple and useful. If this module is only a set of functions or a data packet.
    3. Loop dependency in some cases, we may need functions in modules moduleA and moduleA to depend on some applications. This is circular dependency.
    // js/app/moduleA.jsdefine( [ "require", "app/app"],    function( require, app ) {        return {            foo: function( title ) {                var app = require( "app/app" );                return app.something();            }        }    });
    4. Obtain the module address. If you need to obtain the module address, you can do this ......
    var path = require.toUrl("./style.css");
    5. JSONP
    We can handle the JSONP terminal as follows:
    require( [     "http://someapi.com/foo?callback=define"], function (data) {    console.log(data);});
    9. r. js Compression

    Require. js provides a script for r. js, which can compress all used modules into a script file. r. js can be executed using node. js.

    Before compressing a module, you need to write a configuration file indicating the main module name, the compressed file name, and which modules do not need to be compressed.

    Do not compress modules that are not defined using define, including libraries such as jquery and backbone and Their plug-ins.


    //build.js({    baseUrl: '.',    paths: {    'jquery': 'empty:',    'underscore': 'empty:',    'backbone': 'empty:',  },    name: 'main',    out: 'main.min.js'})
    Compression command:
    node r.js -o build.js
    Learn more about 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.