Modular tool Require.js in JavaScript

Source: Internet
Author: User
Tags script tag jquery library

What is Require.js?

Requirejs is a very compact JavaScript module loading framework and is one of the best implementations of the AMD specification. It can also work with other frameworks, and using Requirejs will certainly improve the quality of your front-end code.

Benefits of using Require.js

1, prevent JavaScript loading blocking page rendering (because it follows the AMD "asynchronous module loading mechanism" specification);

2, using the way the program calls to load JS, to prevent the following ugly scene:

<script type="Text/javascript"Src="A.js"></script><script type="Text/javascript"Src="B.js"></script><script type="Text/javascript"Src="C.js"></script><script type="Text/javascript"Src="D.js"></script><script type="Text/javascript"Src="E.js"></script><script type="Text/javascript"Src="F.js"></script><script type="Text/javascript"Src="G.js"></script><script type="Text/javascript"Src="H.js"></script><script type="Text/javascript"Src="I.js"></script><script type="Text/javascript"Src="J.js"></script>

Getting Started with Require.js

<! DOCTYPE html>"Utf-8"/> <title></title> "Text/javascript"Src="Js/require.js"Data-main ="./main.js"></script> </body>//Main.js (same folder as HTML)Require (['./js/a.js'],function (a) {varDate =NewDate (); A.printdate (date);})//A.jsDefine (['./a-util.js'],function (autil) {varA ={printdate:function (date) {Console.log (autil.agetformatdate (date)); }    }    returnA;})//A-util.jsDefine (['./util.js'],function (util) {varAutil ={agetformatdate:function (date) {returnUtil.getformatdate (Date,2); }    }    returnautil;})//Util.jsdefine (function () {varUtil ={getformatdate:function (date,type) {if(Type = = =1){                return "2017-11-09"; }Else{                return "November 9, 2017"; }        }    }    returnutil;})

Basic APIs in Require.js

A require defines three variables:

define is used to define a module;

require loads the dependent module and executes the post-load callback function. The second parameter of the Require API is callback, a function that is used to handle the logic after loading, such as:

Require (["js/a"],function () {    alert ("load finished  ");})

Requirejs, where require = = = Requirejs, generally uses require more briefly.

Require.js Loading files

In the previous example, the loading module is local JS, but in most cases the page needs to load the JS may be from the local server, other Web site or CDN, so it can not be loaded in this way, we load a jquery library as an example:

 require.config ({paths: {  " jquery   ": ["  http://libs.baidu.com/jquery/2.0.3/jquery   "  "  jquery  " ,  " js/a  "  ],function ($) {$ ( function () {alert (  " load finished       Span style= "COLOR: #800000" > " ); })})

require.configis used to configure the module loading location, simple point is to give the module a shorter and better remember the name, such as Baidu's jquery library address marked jquery , so in require only need to write ["jquery"] can load the JS, local JS We can also configure:

require.config ({paths: {"jquery": ["Http://libs.baidu.com/jquery/2.0.3/jquery"],        "a":"js/a"}}) require (["jquery","a"],function ($) {$ (function () {alert ("Load finished"); })})

The paths configuration will make our module name more refined, paths also has an important function, that is, you can configure multiple paths, if the remote CDN Library is not loaded successfully, you can load the local library, such as:

require.config ({paths: {"jquery": ["Http://libs.baidu.com/jquery/2.0.3/jquery","Js/jquery"],        "a":"js/a"}}) require (["jquery","a"],function ($) {$ (function () {alert ("Load finished"); })})

After this configuration, when Baidu's jquery does not load successfully, it will load the local JS directory of jquery

Precautions for using Require.js

1, when using Requirejs, load the module without writing .js suffix, of course, can not write suffixes;

2, the above example in the callback function found $ parameters, this is the dependent jquery module output variable, if you rely on multiple modules, you can write several parameters to use:

Require (["jquery","underscore"],function ($, _) {    $ (function () {        _.each ([1,2,3],alert);    })})

3, if a module does not output variable values, then do not, so try to write the output module in front, to prevent confusion caused misunderstanding.

Require.js Global Configuration

The above example repeats the require.config configuration, if each page is added to the configuration, it must be very indecent, Requirejs provides a function called "Master data", we first create a main.js:

require.config ({    paths: {        "jquery" : ["http/ Libs.baidu.com/jquery/2.0.3/jquery""js/jquery"],         " a " " js/a "        }})

Then use Requirejs in the following ways in the page:

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

The script tag that loads the Requirejs scripts adds the data-main attribute, this property specifies that the JS will be processed after loading the reuqire.js, and require.config after we add the configuration, we data-main can make each page use this configuration. The page can then be used directly require to load all the module names.

data-mainThere is also an important function, when the script tag specifies the Data-main property, require will default to data-main the specified JS as the root path, what does it mean? As set above data-main="js/main" , after we use require([‘jquery‘]) (do not configure jquery paths), require will automatically load js/jquery.js this file, rather than jquery.js, equivalent to the default configuration.

Require.js third-party modules

By require loading the module is generally required to comply with the AMD specification is used define to declare the module, but part of the need to load non-AMD specification JS, this time need to use another function: Shim,shim interpretation is also difficult to understand, Shim directly translated as "pad", In fact, there is the meaning of this, is mainly used in the following two places.

1. Non-AMD module output, the non-standard AMD module "pad" into a usable module, for example: in the old version of jquery, is not inherited AMD specifications, so can not directly require["jquery", this time need shim, For example, if I use the underscore class library, but he does not implement the AMD specification, then we can configure:

require.config ({    shim:        {"underscore"  : {            " _ " ;        }    }})

With this configuration, we can refer to the underscore module in other modules:

Require (["underscore"], function (_) {    _.each ([1,2,  3], alert);})

2. Plug-in forms of non-AMD modules, we often use the jquery plug-ins, and these plug-ins are not compatible with AMD specifications, such as the Jquery.form plug-in, it is necessary to the form plug-in "pad" into jquery:

require.config ({    shim:        {"underscore"  : {            "  _";        },        "jquery.form"  : {            deps: [ " jquery " ]        }    }})

can also be abbreviated as:

require.config ({    shim:        {"underscore"  : {            "  _";        },        "jquery.form" : ["  jquery"]    }})

After this configuration, we can use jquery after the plugin is loaded.

Require.config (["jquery""jquery.form"], function ($) {    $ (function () {        $ ("#form"). Ajaxsubmit ({...});     })

Modular tool Require.js in JavaScript

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.