Requirejs Getting Started Guide

Source: Internet
Author: User

Recently in the Baidu internship to do a project to use the Require JS this library, has never known, after a rough search to find a very good article, after reading can let you on Require JS operation mechanism, use of the method and why use Require JS There is a basic understanding. Here I will make a simple translation of this article, if there are mistakes and errors in the place to correct.

Original link: http://undefinedblog.com/primer-for-require-js/

Who is suitable to read this article

Have a certain understanding of JavaScript, write a certain size of JavaScript code, especially can grasp the JavaScript anonymous function, callback and other concepts, and hope to understand the use of Require JS, concepts, meaning and so on.

Some basic information

Require JS (official website) is a JavaScript file or module loader, it can be based on different pages of different modules of the needs, according to your settings in order to load and execute all JavaScript files. There are two main purposes of using Require JS:

    • Decoupling code to facilitate code reuse and management
    • Accelerated page loading, built-in optimization engine (requires server support), automatically load dependencies asynchronously, automatically merge all files that need to be loaded into one file, reducing HTTP requests

Require JS at the same time support the integration of JQuery, CommonJS, Node JS, and the browser has a good compatibility (IE 6+, you understand).

No time for Require JS

Below we will start with a module that does not use Require js, to tell you how to decouple your code and use Require JS to load:

"http://www.w3.org/1999/xhtml"> 1</title>1"MessageBox"></div> <script src=".. /scripts/jquery-1.8.2.min.js"Type="Text/javascript"></script> <script type="Text/javascript">varBASEURL ='/api/messenger/'; function ShowMessage (ID) {$.ajax ({Url:baseurl+ID, type:'GET', DataType:'JSON', Success:function (data) {$ ("#messagebox"). HTML (data);        }            }); }        varID = -;    ShowMessage (ID); </script></body>

The above is a very simple and very common AJAX request page, you can see the code in this page is simple, but the coupling is very high, the following we have to decouple the JavaScript code, the different modules independent.

//Module 1, Global setup module        varConfig =(function () {varBASEURL ='/api/messenger/'; return{Baseurl:baseurl}; })();//Module 2, request data module        varDataService =(function ($, config) {varCallapi =function (URL, type, callback) {$.ajax ({url:url, Type:type, DataType:'JSON', Success:function (data) {callback (data);                }                    }); }, GetMessage=function (ID, callback) {URL= Config.baseurl +ID; Callapi (URL,'GET', callback);            }; return{getmessage:getmessage}; }) ($, config);//Module 3, a messenger module in the package that shows the data that Ajax puts back        varMessenger =(function ($, dataservice) {varShowMessage =function (ID) {dataservice.getmessage (ID, function (message) {$ ("#messagebox"). HTML (message);            });            }; return{showmessage:showmessage}; }) ($, dataservice);//Module 4, anonymous function, pass ID, call Messenger's ShowMessage () method (direct execution)(function (Messenger) {varID = -;        Messenger.showmessage (ID); }) (Messenger);

Putting the code in the original, non-refactored page will achieve the same effect. But when we separate these functions, we can reuse some of the code very well.

Let's say we put these 4 modules into 4 separate JS files:

    • Module 1:config.js
    • Module 2:dataservice.js
    • Module 3:messenger.js
    • Module 4:main.js

So, in our HTML page, we need to load these 4 modules sequentially:

"http://www.w3.org/1999/xhtml"> 1</title>1"MessageBox"></div> <script src=".. /scripts/jquery-1.8.2.min.js"Type="Text/javascript"></script> <script src="Config.js"Type="Text/javascript"></script> <script src="Dataservice.js"Type="Text/javascript"></script> <script src="Messenger.js"Type="Text/javascript"></script> <script src="Main.js"Type="Text/javascript"></script></body>

This time, the code can work very smoothly without any problems. But there is a problem to consider: the order in which JS files are loaded. When a module 2 needs to rely on the functionality in Module 1, you must require module 1 to load and then execute the code in Module 2. For simple code (such as the only 4 modules involved in this article) it is good to consider, if there are dozens of modules need to load, then the order of dependency once processing error, it is likely to report xxx is undefined error.

This is the time when Require JS needs to do his own thing.

Require JS basic Operation Definition Module
define (['jquery'],      function ($) {        var'I am A Module',            = function () {                $ ("#messagebox"  ). html (text);            };         return {            showmessage:showmessage        };    });

As you can see, a JavaScript module (such as the above mentioned Config, DataService, messenger, etc.) is wrapped up by a define () function.

where the Define () function accepts 3 parameters:

    • Module name
    • Dependency, passed as an array
    • Module content

But notice that in the module definition above, we do not pass the module name parameter for the following reasons:

Require JS will automatically name the defined module based on the file name (without the suffix name, i.e., ". JS"), so that all files are automatically called when the final optimization (merging all JS files into one). If you show a module named for the definition, then in the future changes (such as changing the file name or module name), Require JS will not be automatically loaded. Therefore, the best practice is: Do not explicitly define the module name, so that the file name becomes the default module name, convenient Require JS management.

After you finish the first argument, look at the second parameter dependency. Dependencies we pass an array of strings, each representing the module names of other modules that need to be preloaded to implement the functionality of this module. As in the previous example, our dependencies are jquery.

The last parameter is the module content that we need to define. In the example above, our module is a function where the formal parameters of the functions are references to dependencies. For example, our module has two dependencies:

define (['modulea','moduleb'],function (A, b) {           //A.blabla (); b.blabla = Ooxx;});

You can use the formal parameters in the module to invoke the modules we rely on separately. It is important to note that the order in which the dependencies are written is consistent with the order of the parameters in the function defined by the module.

In addition, Require JS definition of the module is not necessarily function, can also be a common object, see Require JS document.

Rewrite the decoupled code to Require JS module

We decouple a simple Ajax call into 4 separate modules, and we'll rewrite the 4 modules according to the style of the Require JS definition module.

//Config.jsdefine ([], function () {varBASEURL ='/api/messenger/'; return{Baseurl:baseurl}; });//Dataservice.jsDefine (['jquery','Config'], function ($, config) {varCallapi=function (URL, type, callback) {$.ajax ({url:url, Type:type, DataType:'JSON', Success:function (data) {callback (data);            }                }); }, GetMessage=function (ID, callback) {URL= Config.baseurl +ID; Callapi (URL,'GET', callback);        }; return{getmessage:getmessage}; });//Messenger.jsDefine (['jquery','DataService'], function ($, dataservice) {varShowMessage =function (ID) {dataservice.getmessage (ID, function (message) {$ ("#messagebox"). HTML (message);        });        }; return{showmessage:showmessage}; });//Main.js(function () {requirejs.config ({paths: {'jquery':'.. /scripts/jquery-1.8.2.min'            }        }    ); Require (['Messenger'], function (Messenger) {varID = -;        Messenger.showmessage (ID); }    );}) ();

You may have noticed that the way the module is defined in Main.js seems different from the other 3 modules. Yes, because in a strict sense, main.js is invoking the functionality of the other 3 modules and finally getting the data. So the following is how to define the Require JS module after the final setup and call problems.

Set up and Invoke modules

Require JS provides two ways to set up and invoke a module:

1, define a script tag, and add the Data-main attribute, point to our settings file, and add the src attribute, point to the Require-js.js file (that is, the main library)

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

2, first introduced Require JS Library, and then explicitly set

<script src="Require-js.js"></script> <script>require ({baseUrl:'Scripts',//set the root directory to find all modulesPaths"',//if the corresponding module is not found under BASEURL, add paths to continue searchingshim:{},//load dependencies, passing objects}); require (['Dataservice.js']);//after loading all of the above dependencies, load the modules you have written</script>

See Require JS documentation for detailed parameters.

The above is Require JS some simple use of methods and practices, and then back to IOS development ... return soon!

Files:r9.zip

Requirejs Getting Started Guide (GO)

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.