We know that in other programming languages, there is the concept of a package (command space) that helps us to better manage the code structure. such as the package in Java, module in Python. But in the JS language, in a page execution environment, all the introduced external JS files will be executed in the same global context, do not have a few points: we can not dynamically load the modules we only need; Without the concept of package, code management is confusing. Although the level of language can not be done, but from the above layer to do, so there is the AMD Standard: asynchronous module definition.
Let's say our current file directory is as follows:
We define two core functions in amd.html: Require and define
var modules = {}; var defq = []; function onLoad (script, module) {script.addeventlistener ("load", function () {var deffactory = Defq.shift (); Module.def = deffactory; module.executed = 1; }, False); } function require (Deps, callback) {for (var i = 0; i < deps.length; i++) {var module = { executed:0, Url:deps[i]}; var script = document.createelement ("script"); Script.type = "Text/javascript"; SCRIPT.SRC = Deps[i]; Script.charset = "Utf-8"; OnLoad (script, module); Modules[deps[i]] = module; Document.body.appendChild (script); var id = setinterval (function () {var args = []; for (var i = 0; i < deps.length; i++) {var dep = modules[deps[i]]; if (!dep.executed) {return; }else{Args.push (Dep.def ()); }} clearinterval (ID); Callback.apply (null, args); }, 1000); }; function define (Factory) {Defq.push (factory); }
Now we have defined two JS module files: my/a.js and My/b.js, respectively, as follows:
My/a.jsdefine (function () { return { name: "Tony" }});
My/b.jsdefine (function () { return { name: "Lily" }});
Now we can dynamically load these two module files in any other place, using the following:
Require ([' js/my/a.js ', ' js/my/b.js '], function (A, b) { console.debug (a.name + "" + B.name); });
The above require and define are just a simple AMD idea that is actually much more complex, such as dealing with loops of trust and so complex situations.
Javascript AMD Learning