Front-end AMD, CMD and commonJs - front-end knowledge

Front-end AMD and CMD are produced on a modular basis and are heavily cited.

 AMD That is Asynchronous Module Definition(点击链接可以查看AMD面试题), the Chinese name is the meaning of the asynchronous module definition . It is a specification for modular development on the browser side;

CMD stands for Common Module Definition. The Chinese name means synchronous module definition . It is the output of SeaJs's standardized definition of modules in the promotion process . This specification clarifies the basic writing format and basic interaction rules of modules

CommonJs: Official website: http://www.commonjs.org/     CommonJs is used on the server side, AMD and CMD are used in the browser environment

 

The main functions of these three are:

1. javaScript modular loading is born

2. It is convenient for team members to collaborate, and the code will not be messy

3. Optimization of recording time in network requests

How to use AMD:

AMDjavaScript does not support it, so the requireJs we often use appears. In fact, AMD is the standardized output of RequireJS in the promotion process of module definitions.

requireJS mainly solves two problems

  1. Multiple js files may have dependencies, and the dependent file needs to be loaded into the browser earlier than the file that depends on it
  2. When js is loaded, the browser will stop the page rendering. The more files are loaded, the longer the page loses response time.

The specific writing is as follows:

1. Introduce require.js first in the file,

2. Define a module

3. Load the module

1 define(function(){
2     var keyboard = {
3         'init':function(){
4             console.log(2); 5  } 6  } 7 return keyboard; 8 })

Here is a file keyboard.js we created;

<html>
    <head>
        <meta charset="utf-8">
        <title>requireJs</title>
        <script src="./require.js"></script>
    </head>
    <body>
        <div>Code Test</div>
        <script>
          require(['./keyboard'],function(keyboard){
            keyboard.init();
          })
        </script>
    </body>
</html>

Pay attention to the syntax of require. The file suffix .js can be omitted here. The function parameter defines the name of the module, and the function can be called directly. The following is the compiled code. Here we will see that the keyboard.js we referenced has an additional async attribute, which implements asynchronous loading.

View Code

The syntax is as follows:

requireJS defines a function define, which is a global variable used to define modules

define(id?, dependencies?, factory);
  1. id: optional parameter, used to define the identity of the module, if this parameter is not provided, the script file name (remove the extension)
  2. dependencies: is an array of module names that the current module depends on
  3. factory: Factory method, the module initializes the function or object to be executed. If a function, it should only be executed once. If an object, this object should be the output value of the module

requireLoad a module with a function on the page

require([dependencies], function(){});

The require() function accepts two parameters

  1. The first parameter is an array representing the modules it depends on
  2. The second parameter is a callback function that will be called after the modules specified above are loaded successfully. Loaded modules will be passed in as parameters to the function, so they can be used inside the callback function

The require() function is loaded asynchronously when loading the dependent functions, so that the browser will not lose the response. The callback function specified by it will run only after the previous modules are loaded successfully, which solves the problem of dependencies.

How to use CMD:

1. Introduce seajs

2. Define the module file

3. Import the module

4.seajsAPI:http://yslove.net/seajs/

The code example is as follows:

<html>
    <head>
        <meta charset="utf-8">
        <title>requireJs</title>
        <script src="./seajs.js"></script>
    </head>
    <body>
        <div>Code Test</div>
        <script>
          seajs.use('./keyboard',function(keyboard){
            keyboard.init();
          })
        </script>
    </body>
</html>
/*define(function(){
    var keyboard = {
        'init':function(){
            console.log(2);
        }
    }
    return keyboard;
})*/
// seajs
define(function(require, exports, module) {
    
  // module code
  console.log(require,exports,module);
  module.exports ={
     'init':function(){ console.log(2); } }
 });
/*define(function(){
    var keyboard = {
        'init':function(){
            console.log(2);
        }
    }
    return keyboard;
})*/
// seajs
/*define(function(require, exports, module) {
    
  // module code
  console.log(require,exports,module);
  module.exports ={
     'init':function(){
            console.log(2);
        }
  }

});*/
//seajs second definition
define(function(require, exports, module) {
    
  // module code
  console.log(require,exports,module);
  return {
    'init':function(){ console.log(2); } }
 });

As can be seen from the above, when defining a module through seajs, you need to pay attention to the writing method, one is to return an object directly, the other is module.exports, and then look at the effect of browser parsing

<html><head>
        <meta charset="utf-8">
        <title>requireJs</title>
        <script src="./seajs.js"></script>
    </head>
    <body style="">
        <div>Code Test</div>
        <script>
          seajs.use('./keyboard',function(keyboard){
            keyboard.init();
          })
        </script>
    
</body></html>

When using, you need to use seajs.use(), for more usage, you can refer to the previous api

CMD asynchronous usage:

define(function(require, exports, module) {
    
  // module code
  console.log(require,exports,module);
  return {
    'init':function(){ var $body = document.getElementsByTagName('body')[0]; var html = '<div>This is a prompt style</div>' ; $body.append(html); } } });
/*define(function(){
    var keyboard = {
        'init':function(){
            console.log(2);
        }
    }
    return keyboard;
})*/
// seajs
/*define(function(require, exports, module) {
    
  // module code
  console.log(require,exports,module);
  module.exports ={
     'init':function(){
            console.log(2);
        }
  }

});*/
//seajs second definition
define(function(require, exports, module) {
    var loading = '';
  // module code
  require.async('./loading',function(loading){
      loading = loading.init(); });
   return { 'init':function(){ console.log(2); }, 'loadingInit':function(){ console.log(loading); } } });
<html>
    <head>
        <meta charset="utf-8">
        <title>requireJs</title>
        <script src="./seajs.js"></script>
    </head>
    <body>
        <div>Code Test</div>
        <script>
          seajs.use('./keyboard',function(keyboard){
            keyboard.init();
            keyboard.loadingInit();
          })
        </script>
    </body>
</html>

Loading.js and keyboard.js are not loaded in the compiled html, but they will be displayed in the network,

<html><head>
        <meta charset="utf-8">
        <title>requireJs</title>
        <script src="./seajs.js"></script>
    </head>
    <body style="">
        <div>Code Test</div>
        <script>
          seajs.use('./keyboard',function(keyboard){
            keyboard.init();
            keyboard.loadingInit();
          })
        </script>
    
<div>This is a hint style</div></body></html>

 CommonJs: It is mainly formulated for the performance of JS in the back-end. It is not suitable for the front-end. Why do you say that? The main problems of the front end are 1. Bandwidth, 2. When loading, it needs to be loaded through the network 3. The code needs to be distributed from one server to multiple clients for execution

The modules defined by CommonJS are divided into: {module reference (require)} {module definition (exports)} {module identification (module)}

require() is used to import external modules; the exports object is used to export the methods or variables of the current module, the only export; the module object represents the module itself.

the difference:

1. AMD respects pre-dependency, and declares the modules it depends on when defining modules. 
2. CMD respects nearby dependencies, and requires only when a module is used. 

Reference for this article:

Front end modular

SeaJs

require.js

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324462026&siteId=291194637