Open the Pit! Design and implementation of JavaScript AMD modules

Source: Internet
Author: User

Open a hole and learn to summarize JavaScript's AMD specifications

First write your own simple implementation to put up, and then slowly starting from 0 to explain how AMD, has done its own implementation of an AMD

/*amd*/var DOC = Window.document;var head = Doc.head | | Doc.getelementsbytagname (' head ') [0];var basepath = Getcurrentscript (DOC); basepath = basepath.substring (0, Basepath.lastindexof ('/') +1); noop = function () {};modules = {};function Getemptymodule () {return {deps: [], Offers: [], State:0,factory:noop};}; function Getcurrentscript (DOC) {if (doc.currentscript) {return DOC.currentScript.src;//ff,chrome};var Stack;try { A.B.C ();} catch (e) {stack = E.stack;//Use an error exception to immediately throw a quick get current loaded file path if (!stack && window.opera) {stack = String (e); if (!stack &am p;& window.opera) {stack = (String (e). Match (/of linked script \s+/g) | | []). Join ("");}};}; if (stack) {stack = Stack.split (/[@]/g). Pop ();//Get last line, last space or part after @ stack = stack[0] = = = "("? Stack.slice (1,-1): Stack;return stack.replace (/(: \d+)?: \ d+$/i, ""); Remove the line number with the possible typo character starting position}//ievar nodes = head.getelementsbytagname ("script"); for (var i = 0, node; node = nodes[i++];) {if (node.readystate = = = ' interactive ') {return node.src;};};} functionGetmodulename (URL) {return url.substring (Url.lastindexof ('/') +1, Url.lastindexof ('. js '));} function require (list, factory) {var loaded = 0;var requires = List.length;var args = [];var id = getcurrentscript (DOC); VA R module = Modules[id]?  Modules[id]: Getemptymodule (); module[' factory '] = Factory;modules[id] = module;for (var i=0; i<list.length; i++) {var Depid = basepath+list[i]+ '. js '; Modules[depid] = Modules[depid]? Modules[depid]: Getemptymodule () module[' Deps '].push (depid); if (Modules[depid] && modules[depid].state = = 2 {Modules[depid].offers.push (ID); Loaded++;args.push (modules[depid].exports);//This dependent module is being loaded} else if (modules[depid ] && modules[depid].state = = 1) {Modules[depid].offers.push (ID);//This dependency module has never been loaded} else {//loadjs load module JS, The module JS call Define,define will also require load the dependencies required by this module//thereby function into recursive tracking and load all direct and indirect dependent Modules[depid].offers.push (ID) of this module; Loadjs (depid);};}; if (loaded = = = requires) {module.factory.apply (null, args)};}; function Loadjs (URL) {var module = modules[url];var node = DOC. createelement (' script '); node.onload = Node.onreadystatechange = function () {if (/loaded|complete/i.test ( Node.readystate) | | !node.readystate) {};};   node.src = URL; Head.insertbefore (node, head.firstchild);};  function Findfishedmodules (URL) {var ret = [];var deped = Modules[url];var moduleids = Deped.offers;for (var i = 0; i < Moduleids.length;  i++) {var id = Moduleids[i];var Deps = Modules[id].deps;var flag = False;for (var j = 0; J < Deps.length; J + +) {var dep = Modules[deps[j]];if (Dep.state = = 2 | | deps[j] = = URL) {flag = true;}; if (dep.state! = 2) {flag = False;break;};}; if (flag) {console.info (' module ' +getmodulename (ID) + ' available '); Ret.push (id);};}; return ret;}; function Firefactory (root) {var finshedids = findfishedmodules (root); for (var i = 0; i < finshedids.length; i++) {var m Odule = modules[finshedids[i]];module.factory.apply (null, Getdepsmodules (module.deps)); Firefactory (FinshedIds[i]) ;};}; function Getdepsmodules (deps) {var args = [];for (var i = 0; i < deps.length; i++) {var dep = Deps[i];args.push (modules[dep].exports);}; return args;}; function define (Deps, factory) {var id = getcurrentscript (DOC);//If this module does not rely on installing the module immediately if (deps.length = = 0) {Modules[id]. Exports = factory.apply (null); modules[id].state = 2;//A series of triggering installation Firefactory (ID) from the dependent leaves; return;}; Require (Deps, function () {var _deps = [];for (var i = 0; i < deps.length; i++) {_deps.push (basepath+deps[i]+ '. js ')}; Modules[id].exports = factory.apply (null, Getdepsmodules (_deps)); modules[id].state = 2;});


Related Article

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.