AMD vs. Cmd from a code enthusiast perspective (RPM)

Source: Internet
Author: User
Tags define function node server

As browsers become more sophisticated, the front end has been more than just transduction, and the front end has been comparable to desktop applications in some ways. Increasingly large front-end projects, increasingly complex code, front-end developers have a strong need for modularity. Then node appeared, followed by node Commonjs, which is a JS modular solution, Like node. JS is mainly used for server programming, the loaded module files are usually already present on the local hard disk, so it is faster to load, regardless of the way asynchronous loading, the CommonJS load module is synchronous, so only the loading is complete to perform the subsequent operation. But the browser environment is different from node, the browser to get a resource must be sent HTTP request, from the server side, the adoption of synchronous mode will inevitably block the browser process of suspended animation phenomenon. In this respect, Dojo has made a great attempt, early dojo is the use of xhr+eval, the result is conceivable, blocking phenomenon is inevitable. Then there is a non-blocking loading script in the development of a wide range of applications, in this foundation combined with the COMMONJS specification, the front-end modular approach ushered in two scenarios: AMD, CMD.

Borrow Sanzang mage A word: Man is a man's mother born, Demon is demon his mother born. This is not an elegant remark, but it is quite appropriate to use here. AMD is the normalized output of the module definition in the Requirejs, and the CMD is seajs widely recognized in the promotion process. Requirejs, author of the Dojo loader, James Burke,seajs, is from the domestic front-end master Yuber. The difference between the two, Yuber in 12 years, said:

Requirejs and Seajs are very good module loaders, the difference is as follows: 1. There are differences between the two positions. Requirejs want to be a browser-side module loader, and also want to be a module loader for Rhino/node and other environments. Seajs is focused on the Web browser side, and through node extension can easily run on node server side 2. There are differences in the standards that they follow. Requirejs follows the AMD (asynchronous module definition) specification, and Seajs follows the CMD (Generic module definition) specification. The different specifications lead to the difference between the two APIs. Seajs is more concise and elegant, closer to CommonJS modules/1.1 and Node Modules specifications. 3. There are differences between the two community concepts. Requirejs is trying to get a third-party class library to modify itself to support Requirejs, and only a handful of communities have adopted it. Seajs not strong push, and adopt the way of self-encapsulation to "Haina Rivers", now has a more mature packaging strategy. 4. There is a discrepancy between the code quality. Requirejs is no obvious bug,seajs is obviously no bug. 5. There is a difference between the two for debugging and other support. Seajs through the plug-in, can realize the Fiddler automatic mapping function, but also can realize automatic combo and other functions, very convenient and convenient. Requirejs has no support in this regard. 6. There is a difference in the plug-in mechanism. Requirejs is to take the form of a reserved interface in the source code, the source has been written for plug-ins. The plug-in mechanism adopted by SEAJS is consistent with Node's approach: open itself, allowing plug-in developers to directly access or modify, and thus very flexible, can implement various types of plug-ins.

About the difference between the two, the previous statement prepared:

    • About CommonJS AMD CMD UMD

    • Let's talk about it. Browser Resource load Optimization

    • The biggest difference between Seajs and Requirejs

    • YUI Modules and Amd/cmd, which way is better?

    • JAVASRIPT Module Specification-AMD specification and CMD specification introduction

In this paper, we only from the point of view of code enthusiasts to see the API, module management, loading, implementation of the similarities and differences.

The most significant difference between the AMD and CMD specifications is the execution period of the dependent module, which explicitly requires deferred execution (execution must be lazy). This can be seen from both the function signatures of the module definition method define:

AMD in define is defined as follows:
Define (ID?, dependencies, Factory);
    • The id:string type, which specifies the ID of the module when it is defined; Optionally, if omitted, the module ID is used by default to use the module IDs of the response script requested by the loader.
    • Dependencies is an array literal of module ID for a module that defines the dependencies that are required. These dependencies must be parsed before the factory method executes, and the parsed value should be passed as a parameter to the factory function, and the factory's parameter position conforms to the module's index in the dependency.
    • Factory is a parameter or an object that is used to perform the initialization of a module. If factory is a function, it should only be used for execution once. If the factory parameter is an object, this object is used as the output value of the module. If the factory function returns a value (object, function, any value that can be cast to true), this value will be used as the output value of the module.

Define (["./a", "./b"], function (A, b) {  //begin  a.dosomething ();  B.dosomething ();});

The modules in CMD are defined as follows:

Define (function (Require, exports, module) {  //The module code goes here});
A module uses the Define function to define
    1. The Define function accepts only one module factory as a parameter
    2. Factory must be a function or other valid value
    3. If factory is a function, the first three must be "require", "exports", "module" if the parameter is specified
    4. If factory is not a function, then the exports property of the module is set to that valid object
Define (function (Require, exports, module) {  //begin  require ("./a"). DoSomething ();  Require ("./b"). DoSomething ();});

It should be mentioned that the loading of the dependent modules is consistent, and that the dependent modules are loaded when factory executes. From the code point of view, AMD's factory at begin A and B are all executed, while the A and B modules in CMD are loaded at begin, but have not yet been executed and need to call require to execute the dependent modules. This is the deferred execution that is highlighted in CMD. If this example is not obvious, let's look at conditional dependencies:

Amd:

Define (["./a", "./b"], function (A, b) {  //begin  if (true) {    a.dosomething ();  } else {b.dosomething (); c9/>}  //end});

Cmd:

Define (function (require) {   //BEGIN  if (some_condition) {    require ('./a '). dosomething ();  } else {    require ('./b '). sosomething ();  }  END});

Conditional dependency means that we use dependencies based on conditions, and A and B modules need to be executed once in AMD at the begin position. At the beginning of CMD, A and B are not executed, and at end, only one of A and B is actually executed.

So the question is, JavaScript as a scripting language, code must be executed sequentially, as the AMD and CMD implementations, how does Requirejs and Seajs know all the files that need to be loaded? How do you do asynchronous loading? The code in Seajs,factory is definitely executed sequentially, but this has to cause a blocking load at require, and how does she guarantee asynchronous loading?

  every thought of excellence has a simple code implementation . So both AMD and CMD face the following issues:

1, the module how to register, define function have done what?  2. How do they know the dependencies of the modules? 3, how to do asynchronous loading?  Especially how does SEAJS do asynchronous load deferred execution? The first law of dialectics: There is an organic connection between things. AMD and CMD have borrowed from the COMMONJS, the macro level must have consistency, such as the overall processing process: module load resolution to the execution of the process has gone through 6 steps: 1, the entry into the program 2, the first thing to do is to build a module warehouse (this is the key to prevent repeated loading module), The JavaScript native object object is most suitable, the key represents the module Id,value represents each module, processes the main module 3, registers a module to the module warehouse, a module contains at least four attributes: ID (unique identifier), Deps (the ID array of the dependency), Factory (module's own code), status (module state: not loaded, loaded not executed, executed, etc.), in the code of course, or object is the most appropriate 4, the module is a JavaScript file, using non-blocking method (dynamically create a script tag) load module
scriptelement= document.createelement (' script '); scriptelement.src = Moduleurl;scriptelement.async = true; Scriptelement.onload = function () {...}; Document.head.appendChild (scriptelement);

5, after the module has been loaded, get dependencies (AMD, cmd difference), change the module status, by Statuschange, detect the dependencies of all modules.

Because Requirejs and SEAJS follow the specifications, Requirejs can easily get the current module dependencies in the Define function. There is no need to rely on claims in Seajs, so special handling is required to get dependencies. The factory method is used to do ToString and then matches the dependencies in the regular match, such as the presence of require (./a), which detects the need to rely on the a module.

Satisfying both non-blocking and sequential execution requires some preprocessing of the code, as determined by the CMD specification and browser environment characteristics.

6, if the module's dependencies are fully loaded (AMD needs to be completed, CMD only need to load the file, note that this time factory has not been executed, when using require request the module, factory will execute, Therefore, the performance of the SEAJS is less than REQUIREJS), the main module to execute the factory function; otherwise go to step 3.

Finally, whether Requirejs or Seajs have been widely used in web development, the actual selection should be based on the following aspects of the overall balance selection:

1, the function can meet the needs of the project 2, documentation, demo details 3, the framework of learning curve 4, community activity

AMD vs. Cmd from a code enthusiast perspective (RPM)

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.