JavaScript Advanced Modular--require.js__js

Source: Internet
Author: User
require.js: Requirejs is a very compact JavaScript module loading framework, one of the best implementations of the AMD (asynchronous module Definition, asynchronous modular loading mechanism) specification. The latest version of the Requirejs compression only 14k, is very lightweight. It can also work with other frameworks, and using Requirejs will definitely improve the quality of our front-end code. first, let's take a look at a common page JS load
<! DOCTYPE html>
Run Result:

at this point, if we do not operate the pop-up box, the page will not be loaded, there will be no page content, this is not what we want to achieve results. Below we use require.js to do the operation:

Index.html

<! DOCTYPE html>
Index.js
define (function () {
    Console.log ("This is a test!");
    function test () {
        console.log ("Haha,i am a test!");
    }
    Test ();
});
First, the page is no longer imported test02.js, just imported Requirejs, followed by the Require () method in JavaScript, in which passed an array of parameters, the argument is the JS file we want to import "path + file name." the results of this operation:


as you can see, the page content has already appeared. It's not like we've traditionally been waiting for JS to run after the page is loaded, but the page after the completion of the load to run the JS code, so in the operational efficiency is greatly improved. based on the above code, we can analyze the basic API of Requirejs: Requirejs will define three variables: Define,require,requirejs require== Requirejs, the general use of require more brief. Define is used to define a module require load dependent modules (reference-defined modules) and perform the loaded callback function require has three parameters:

Require (["Js/index", "js/index01"],function () {
                console.log ("functions performed when JS is loaded successfully");
            },function () {
                Console.log ("function to be executed when JS fails to load)";
First parameter: Defines the dependencies in the require, the arguments must be of an array form, and even if there is only one dependency, you must also use the array form to pass the argument.
//second parameter: is a callback function, which is used to handle the logic after loading, triggering//third parameter when all modules have been loaded
: It is also a callback function to deal with the failure of the module after loading. As the above code, JS does not define index01.js this file, so out call this callback function.
Load Network Files before we loaded are the local JS file, but, sometimes we need to load the file on the network, then how to load it. Below we will introduce how to load the JS file on the network. Let's now take an example of loading a jquery.js file:
Baidu CDN Public Library jquery Address:      http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js 
//jquery official address:           https:// Code.jquery.com/jquery-3.1.1.js
//NOTE: The network can not be added to the suffix, otherwise
require.config ({
    paths: {
        // To the library on the network go to a name: jquery
        "jquery": ["https://code.jquery.com/jquery-3.1.1"]
    }
});
require (["jquery", "js/test01", "js/test02"],function () {
    alert ("Page load succeeded ~ ~");
},function () {
    alert ("Page load failed ~ ~")
});
Note When fetching files on the network:

1, the Config method parameter is an object
2, the value of paths is also an object
3, when we get the name of the library on the network is arbitrary, but suggest a meaningful name, others can by name to know your network resources are what resources
4, the value of the library is an array, meaning that you can write multiple simultaneous, to prevent network anomalies from
5, Special note: The network resource path can not be a suffix name, or to get
6, we can also first to go to the network to take, if not, and then locally, to reduce the pressure of local services (belong to the project optimization).

Require.config ({
    paths: {
        //This configuration, reduce the pressure on the local server
        "jquery": ["Https://code.jquery.com/jquery-3.1.1.js", "JS /jquery-1.8.3 "]
    }
});
require (["jquery", "js/test01", "js/test02"],function () {
    alert ("Page load succeeded ~ ~");
},function () {
    Alert ("Page load failed ~ ~")
});
Also, we can configure the local configuration into paths:
Require.config ({
    paths: {
        //This configuration, reduce the pressure on the local server
        "jquery": ["https://code.jquery.com/jquery-3.1.1", "JS /jquery-1.8.3 "],
        ///will be the same as the local JS file configuration, after
        the reference" test01 ": [" js/test01 "],
        " test02 ": [" js/test02 "]
    }
});
require (["jquery", "test01", "test02"],function () {
    alert ("Page load succeeded ~ ~");
},function () {
    alert ("Page load failed ~ ~")
});
The above example repeats the Require.config configuration, if each page is added to the configuration, must appear very indecent, Requirejs provides a function called "Master data", we first create a main.js:
Require.config ({
    paths: {
        //This configuration, reduce the pressure on the local server
        "jquery": ["https://code.jquery.com/jquery-3.1.1", "js/ jquery-1.8.3 "],
        ///will be the same configuration of the local JS file, then refer to
        " test01 ": [" js/test01 "],
        " test02 ": [" js/test02 "]
    }
);
then use the following method in the page to use Requirejs:
<script type= "Text/javascript" src= "js/require2.1.11.js" ></script>
<script type= "text/" JavaScript "src=" Js/main.js "></script>
<script type=" Text/javascript ">

    require ([" jquery "," T1 "," T2 "],function () {
        alert (" Page load succeeded ~ ~ "),
    },function () {
        alert (" Page load failed ~ ~ ")
    });

</script>
The official provides a way to label properties:
<script data-main= "Js/main" src= "Js/require2.1.11.js" ></script>

All of the configuration and import JS are placed in the main.js, so that the page as long as a label on the line. The code demonstrates the following:

test01.js--defines a JS module
define (function () {
    function test () {
        Console.log ("This is Test01.js");
    }
    Test ();

    $ ("P"). CSS ("Color", "#DB7093");
Main.js--requirejs Global Configuration
require.config ({
    paths:{
        "jquery": ["jquery-1.8.3"],
        "test": ["test01 "]
    },
    shim:{
        " test ": [" jquery "]
    }
});
Require (["Test"],function () {
    console.log ("success!");
});
index.html--at this point, the introduction of JS file only one line of code
<! DOCTYPE html>

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.