AMD of JavaScript modular programming

Keywords: Front-end JQuery Vue Javascript Programming

Simply put, AMD is the abbreviation of "Asynchronous Module Definition", which means "Asynchronous Module Definition". It loads the module asynchronously, and the loading of the module does not affect the running of the subsequent statements. All statements that depend on this module are defined in a callback function, which will not run until the loading is completed.

Function of require.js

  • Realize the asynchronous loading of js file to avoid the web page losing response;
  • Manage the dependencies between modules to facilitate the code writing and maintenance.

First, introduce the requireJS file, and specify the entry file (main module) on the script tag:

 <meta charset="UTF-8">
 <title>javascript Modular programming</title>
<script type="text/javascript" src="" defer async data-main="js/main.js"></script>

Next, you need to configure main.js:

// Module loaded configuration
 // Base directory if each module is not in a base directory
 // Specify directly in paths without baseUrl
 baseUrl: "lib",
 paths: {
 'jquery': 'jquery',
 'vue': 'vue.min',
 'pagination': 'my-pager'
 // The ship property is used to configure incompatible modules. Each module is defined as follows:
 // (1) the exports value (the variable name of the output) indicates the name of the external call of this module
 // (2) deps array indicates the dependency of the module
 // For example, jq plug-ins can be defined in this way
 shim: {
 'jquery.scroll': {
 deps: ['jquery'],
 exports: 'jQuery.fn.scroll'
 // requireJS also has a series of plug-ins
 // [Plugins](
// The main module depends on other modules, so you need to use the require() function defined by the AMD specification
// require([modules], function (modules) { });
require(['jquery', 'vue', 'pagination'], function ($, Vue, pagination) {

For example, pagination in the above example:

(function (factory) {
 if (typeof exports === 'object') {
 // Node/CommonJS
 factory(require('document'), require('window'));
 } else if (typeof define === 'function' && define.amd) {
 // AMD
 define(factory(document, window));
 } else {
 // Browser globals
 factory(document, window);
}(function (document, window) {
 var Test = {
 a: 1
 if (typeof module != 'undefined' && module.exports) {
 module.exports = Test;
 } else if (typeof define == 'function' && define.amd) {
 define(function () { return Test; });
 } else {
 window.Test = Test;

Posted by chaser7016 on Tue, 10 Dec 2019 02:34:53 -0800