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

Start by putting a simple implementation of your own, and then slowly start with 0 to explain AMD, and how to do it yourself to achieve an AMD

(Function (w, DOC) {var _$ = W.$;var head = Doc.head | | Doc.getelementsbytagname (' head ') [0];var html = Doc.documentelement;var = Doc.dispatchevent;var BasePath = Getcurrentscript (DOC); basepath = basepath.substring (0, Basepath.lastindexof ('/') + 1); var hasown = Object.prototype.hasownproperty;var toString = Object.prototype.tostring;var Class2type = {};var NoOp = function () {}; var as = function () {if (this = = W) {return new as (arguments),} else {console.info (this);}}; As.prototype = {Constructor:as}; As.fn = As.prototype; As.extend = function () {var args = arguments;if (args.length = = = 2) {var target = Args[0];var Source = args[1];for (var att R in Source) {target[attr] = source[attr];};} else {for (var i = 0, len = args.length; i < Len; i++) {var obj = args[i];for (var attr in obj) {as[attr] = obj[attr];} ;};};};/ *AMD module starts */var 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 error exception to immediately throw high speed get current loading file path if (!stack && window.op ERA) {stack = String (e), if (!stack && 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 from the starting position of the typo character that may exist}//ievar nodes = head.getelementsbytagname ("script"); for (var i = 0, node; node = nodes[i++];) {if (node.readystate = = = ' interactive ') {return node.src;};};} function Getmodulename (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); Co Nsole.info (' Load ' +getmodulename (ID) + ' module needs to rely on ' + list+ ' module ') var 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]? mod Ules[depid]: Getemptymodule () module[' Deps '].push (depid); if (Modules[depid] && modules[depid].state = = 2) { Console.info (Getmodulename (depid) + ' dependency has been loaded in advance '); Modules[depid].offers.push (ID); Loaded++;args.push (modules[depid].exports);//This dependent module is being loaded in} else if (Modules[depid] && modules[depid].state = = 1) {Console.info (Getmodulename (depid) + ' dependent on loading '); Modules[depid].offers.push (ID )///This dependent module has never been loaded} else {//loadjs loading module JS, module JS call define,define will require load the module required// Thus the function enters recursive tracing and loads this module all directly and indirectly relies on console.info (' first load dependent module ' + getmodulename (depid)); Modules[depid].offers.push (ID); Loadjs (depid);};}; if (loaded = = = requires) {module.factory.apply (null, args); module.state = 2;};}; Window.require = As.require = require;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); module.state = 1;//console.info (' Loading module ' +getmodulename (URL) );};  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) {Console.info (' lookup depends on module installation of ' +getmodulename (root) + '); var finshedids = Findfishedmodules (root); for (var i = 0; i < finshedids.length; i++) {var module = Modules[finshedids[i]];console.info (g Etmodulename (Finshedids[i]) + ' module full dependency has been able to install complete, can run callback function '); var exports = module.factory.apply (null, Getdepsmodules ( module.deps)); module.state = 2;if (Exports) {module.exports = Exports;console.info (' Import ' +getmodulename (Finshedids[i]) + ' module ');} else {break;}; 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);//Assume that this module is not dependent on installing the module right away (deps.length = 0) {Modules[id]. Exports = factory.apply (null); modules[id].state = 2;//from dependent leaves up to a series of triggering installations Console.info (' module ' +getmodulename (ID) + ' loading complete '); firefactory (id); 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;console.info (' module ' + Getmodulename (ID) + ' onboarding complete '); Firefactory (ID);});}; Window.define = As.define = DEFINE;/*AMD module end *///exposure as function w.$ = W.as = as;}) (self, self.document);


Open the Pit! Design and implementation of JavaScript AMD modules

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.