Front-End modular, AMD and CMD

Source: Internet
Author: User
Tags script tag

Recently in the study of CMD and AMD, on the Internet to see a good article, tidy up to see.
In the early days of JavaScript development is to achieve a simple page interaction logic, a few words can be; now CPU, browser performance has been greatly improved, many pages logically migrated to the client (form validation, etc.), With the advent of the web2.0 era, Ajax technology has been widely used, jquery and other front-end libraries emerge, the front-end code is expanding

While JavaScript has been shaken as an embedded scripting language, JavaScript does not provide any obvious help for the organization's code, not even the concept of classes, let alone modules (module), JavaScript's extremely simple code organization specification is not enough to harness such a large scale of code modules

Since JavaScript cannot handle such large scale code, we can learn how other languages deal with large-scale programming, there is an important concept in Java--package, logically related code is organized into the same package, within the package is a relatively independent kingdom, Don't worry about naming conflicts or anything, so external if used. Direct import corresponding to the package can be

Import java.util.ArrayList;
Unfortunately, JavaScript does not provide similar functionality in the design time, and developers need to simulate similar functionality to isolate and organize complex JavaScript code, which we call modularity.

A module is to implement a specific function of the file, with the module, we can more easily use other people's code, want what function, loaded what module. Module development needs to follow a certain specification, the split is all messed up

The process of the formation of norms is painful, the pioneer in the front of the slash-and-burn, nascent stage began, developed to take shape now, a simple understanding of this extraordinary course

function Encapsulation

When we talk about functions, we mention that a function is a set of statements that implement a particular logic, and that JavaScript's scope is based on functions, so it's natural to take functions as the first step in modularity, and writing a few related functions in a file is the starting module.

function fn1 () {
    statement
}

function fn2 () {
    statement
}

So when you need to clip the file in the function, call the function.

The disadvantage of this approach is obvious: pollution of global variables, there is no guarantee that no variable name conflicts with other modules, and module members are not related to each other.

Object

In order to solve the above problem, the object is written in a way that can encapsulate all the module members in an object

var mymodule = {
    var1:1,

    var2:2,

    fn1:function () {}

    ,

    fn2:function () {

    }
}

So we reference the corresponding file when we want to call the module, and then

Mymodule.fn2 ();
This avoids the variable pollution, as long as the module name is guaranteed to be unique, while the members of the same module also have a relationship

Seemingly good solution, but also flawed, external can be arbitrarily modified internal members

MYMODEL.VAR1 = 100;
This can cause unexpected security problems.

Execute function now

You can achieve the purpose of hiding details by executing the function immediately

var MyModule = (function () {
    var var1 = 1;
    var var2 = 2;

    function fn1 () {

    }

    function fn2 () {

    } return

    {
        fn1:fn1,
        fn2:fn2
    };
}) ();

This way, outside the module, we can't modify the variables and functions we haven't exposed.

The above approach is our modular basis, at present, the prevailing JavaScript module specifications are mainly two: Commonjs and AMD

Commonjs

Let's start with COMMONJS, because there's no modular programming at the end of the page, just a page JavaScript logic, but it can work, but it has to be a module on the server, so while JavaScript has grown over the web for so many years, The first popular modular specification is brought by server-side JavaScript applications, and the COMMONJS specification is carried forward by Nodejs, marking the formal stage of JavaScript modular programming.

1. Definition Module
According to the COMMONJS specification, a separate file is a module. Each module is a separate scope, that is, a variable defined within the module that cannot be read by another module unless it is defined as a property of the global object

2, module output:
Module has only one exit, Module.exports object, we need to put the contents of the module want output into the object

3, Loading module:
The load module uses the Require method, which reads a file and executes it, returning the Module.exports object inside the file

See an example

Module definition mymodel.js

var name = ' Byron ';

function Printname () {
    console.log (name);
}

function Printfullname (firstName) {
    console.log (firstName + name);
}

Module.exports = {
    printname:printname,
    printfullname:printfullname
}

//load module

var Namemodule = require ('./mymodel.js ');

Namemodule.printname ();

Different implementations of the require when the path has different requirements, the general situation can omit JS extension, you can use the relative path, you can use the absolute path, and even can omit the path directly using the module name (provided that the module is the System built-in module)

awkward browsers

Looking closely at the code above, you will find that require is synchronized. The module system needs to read the contents of module files synchronously and compile and execute to get the module interface.

This is simple and natural to implement on the server side, however, there are a lot of problems to be implemented on the browser side.

Browser side, the best and easiest way to load JavaScript is to insert a script tag in the document. But the script tag is inherently asynchronous, and the traditional COMMONJS module does not load properly in the browser environment.

One solution is to develop a server-side component that provides static analysis of the module code and returns the module to the browser side with its list of dependencies. This works well, but requires the server to install additional components, and therefore to adjust a series of underlying architectures.

Another solution is to encapsulate the module definition with a set of standard templates, but what is the difference between how and how the module should be loaded? AMD

AMD is the asynchronous module definition, and the Chinese name is the meaning of the asynchronous module definition. It is a specification for modular development at the browser end

Because it is not JavaScript native support, using the AMD Specification for page development requires the corresponding library function, that is, the famous Requirejs, in fact, AMD is requirejs in the promotion process of the modular definition of the standardized output

Requirejs mainly solves two problems

1, a number of JS files may have dependencies, dependent files need to be earlier than rely on its files loaded into the browser
2, JS load when the browser will stop page rendering, loading files more, the page lost response time longer
Look at an example of using Requirejs

Define Module Mymodule.js
define ([' dependency '], function () {
    var name = ' Byron ';
    function Printname () {
        console.log (name);
    }

    return {
        printname:printname
    };
}

; Load module
require ([' mymodule '], function (my) {
my.printname ();
});

Grammar

Requirejs defines a function define, which is a global variable, used to define a module

Define (ID, dependencies, Factory); ID: Optional parameter that defines the module's identity and, if not provided, the script filename (remove extension name) dependencies: is an array of module names that the current module relies on factory: The Factory method, the module initializes the function or object to execute. If it is a function, it should only be executed once. If it is an object, this object should be the output value of the module
Loading modules using the Require function on the page

require ([dependencies], function () {});
The Require () function accepts two arguments the first argument is an array that represents the dependent module The second parameter is a callback function, and the module specified by the current plane is successfully loaded and will be invoked. The loaded modules are passed in as arguments to the function so that they can be used inside the callback function

The Require () function is loaded asynchronously when the dependent function is loaded, so that the browser does not lose its response, and the callback function that it specifies will run only after the previous module has been loaded successfully, resolving the problem of dependency. CMD

CMD is the common module definition of common modules, CMD specification is developed in China, like AMD has a requirejs,cmd have a browser implementation seajs,seajs to solve the problem and the same requirejs, But the timing of the module definition and module loading (can be said to run, parse) is different

Grammar
Sea.js a module to a file, followed by a unified formulation
Define (ID, deps?, Factory)
Because CMD advocates a file of a module, so often use the filename as module ID cmd respected rely on the nearest, so generally not in the parameters of define write dependencies, write in factory

Factory is a function that has three parameters, function (require, exports, module) require is a method that takes the module identifier as the unique parameter to obtain the interface provided by other modules: require (ID) exports is an object that is used to provide external modules interface module is an object that stores some of the properties and methods associated with the current module
Look at an example:

Define module  mymodule.js
define (function (Require, exports, module) {
  var $ = require (' jquery.js ')
  $ (' div ') . addclass (' active ');
};

Load Module
seajs.use ([' mymodule.js '], function (my) {

});
the difference between AMD and CMD

On the difference between these two can be found on the internet a pile of articles, a simple summary

The most obvious difference is that the dependencies are handled differently when the module is defined

1, AMD highly dependent on the predecessor, in the definition of the module must declare its dependent modules
2, Cmd praised the nearest dependence, only in the use of a module to go to require
This distinction has advantages and disadvantages, but grammatical gaps, and requirejs and SEAJS support each other's writing

The biggest difference between AMD and CMD is that the timing of the dependent modules is handled differently, and the attention is not the timing or the manner of loading.

Many people say Requirejs is asynchronous loading module, SEAJS is the synchronous loading module, so understanding is actually inaccurate, in fact, the load module is asynchronous, but AMD relies on the front, JS can easily know the dependent module who, immediately loaded, and cmd nearest dependence, Need to use the module into a string parsing to know that rely on those modules, which is also a lot of people criticized CMD point, sacrificing performance to bring the convenience of development, in fact, parsing module with a short time to be able to ignore

Why do we say the two difference is that depending on the module execution timing is different, why many people think that ADM is asynchronous, CMD is synchronized (except for the name of the reason ...). )

are also asynchronous loading modules, AMD in the loading module will be implemented after the module, all modules are loaded after the execution will enter the require callback function, the implementation of the main logic, such an effect is dependent on the implementation of the module and writing order does not necessarily coincide, see the network speed, which first download down, which first implementation, But the main logic must be executed after all dependent loads have been completed

CMD after loading a dependent module does not execute, just download, after all the dependent modules loaded into the main logic, encountered require statements to execute the corresponding module, so that the execution sequence of the module and the writing sequence is exactly the same

This is also a lot of people say that the AMD user experience is good, because there is no delay, dependent module ahead of schedule, cmd performance is good, because only when the user needs to execute the reason

Turn from: http://blog.csdn.net/jackwen110200/article/details/52105493

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.