My module load system v6

Source: Internet
Author: User

The module system is part of the core modules of our framework and is fully integrated with domready. Of course, the core module also provides other common methods, such as several groups, type determination, and simple event binding... this version mainly optimizes the type determination and rewrites module loading to handle the issue of circular dependency in a more elegant way.

(Function (global, DOC) {VaR _ dom = Global. dom, hash = "#", namespace = escape (Doc. URL. split (hash) [0]), head = Doc. head | Doc. getelementsbytagname ("head") [0], class2type = {"[object htmldocument]": "document", "[object htmlcollection]": "nodelist ", "[object staticnodelist]": "nodelist", "[object ixmldomnodelist]": "nodelist", "[object domwindow]": "window", "null ": "null", "Nan": "Nan", "U Ndefined ":" undefined "}, tostring = class2type. tostring;/*** mix, add more members to an object * @ Param {object} target object * @ Param {object} source attribute package * @ Param {Boolean | undefined} override * @ return {object} target object */function mix (target, source, override) {var key, ride = (override = void 0) | override; For (key in source) {If (ride |! (Key in target) {target [Key] = source [Key] ;}} return target ;}/ *** @ Class Dom * Dom framework has two namespaces, * The first is escape (Doc. URL. split ("#") [0]), dynamically generated based on the page address * The second is Dom, we can use the alias mechanism to override it * @ namespace Dom */var dom = function (expr, context) {If (typeof expr = "function") {Dom. ready (expr, true);} else {If (! Dom. FN) throw "must load the 'node' module! "Return new Dom. FN. init (expr, context) ;}} mix (DOM, {UUID: 1, HTML: doc.doc umentelement, head: Head, rword:/[^,] +/g, rreadystate: /loaded | complete | undefined/I, "@ name": "dom", "@ debug": True, "@ emitter": Doc. dispatchevent? "Addeventlistener": "attachevent",/*** alias mechanism (equivalent to jquery's noconflict) * @ Param {string} Name new namespace */exports: function (name) {_ DOM & (Global. DOM = _ DOM); name = Name | Dom ["@ name"]; DOM ["@ name"] = Name; global [name] = global [namespace] = This ;}, /*** array ** @ Param {arraylike} nodes the array object of the class to be processed * @ Param {number} start (optional. The starting subscript of the part to be extracted. If it is a negative number, * @ Param {number} end is optional. Specifies where to end the selection * @ return {array} */slice: function (nodes, start, end) {for (VAR I = 0, n = nodes. length, result = []; I <n; I ++) {result [I] = nodes [I];} If (arguments. length> 1) {return result. slice (START, (end | result. length);} else {return result ;},/*** curry * @ Param {Any} A * @ return {function} new function */K: function (a) {return function () {return a ;}},/*** is used to obtain the data type or determine the data type * @ Pa What Ram {Any} OBJ wants to detect * @ Param {string} STR the type to be compared * @ return {string | Boolean} */type: function (OBJ, STR) {var result = class2type [(OBJ = NULL | OBJ! = OBJ )? String (OBJ): tostring. call (OBJ)] | obj. nodename | hash; If (result. charat (0) === hash) {// compatible with legacy browsers and handle some situations, such as window. opera if (obj. window = OBJ) {result = 'window'; // returns the constructor name} else if (obj. nodetype = 9) {result = 'document'; // returns the constructor name} else if (obj. callee) {result = 'arguments '; // returns the constructor name} else if (isfinite (obj. length) & obj. ITEM) {result = 'nodelist'; // processing node set} else if (obj. open & obj. send) {resul T = "XMLHttpRequest";} else {result = tostring. call (OBJ ). slice (8,-1) ;}}if (STR) {return STR === result;} return result ;}, /*** for debugging * @ Param {string} s */log: function (s) {Global. console & Global. console. log (s) ;},/*** generates objects with unified key values for high-speed judgment * @ Param {array} array * @ Param {number} Val (optional, the default value is 1 * @ return {object} */oneobject: function (array, Val) {If (typeof array = "string") {array = array. ma Tch (DOM. rword) | []} var result = {}, value = Val! = Void 0? VAL: 1; for (VAR I = 0, n = array. length; I <n; I ++) {result [array [I] = value ;}return result ;}); "Boolean, number, String, function, array, date, Regexp, window, document, arguments, nodelist, XMLHttpRequest ". replace (Dom. rword, function (name) {class2type ["[object" + name + "]"] = Name ;}); // http://wp.moooori.com/archives/1911 var rmodule =/([^ (\ s] + )\(? ([^)] *) \)? //, // Rreadystate =/loaded | complete | undefined/I, method = Doc. dispatchevent? "OnLoad": "onreadystatechange", stack = [], // used to place negative callback checks = [], // used to place forward callback or wrapper function status of the module itself = {}; // used to record the loading status of each module 0 not registered 1 registered 2 loaded 3 executed/*** used to simulate the opera script onerror * http://d.hatena.ne.jp/NeoCat/20110206/1296934235 * @ Param {string} Name Module name * @ Param {string} URL module path * @ Param {element} node is the Script node temporarily generated when this module is loaded */function fixoperaerror (name, URL, node) {var IFRAME = Doc. createelement ("I Frame "); var code = '<SCRIPT src ="' + DOM. baseurl + '"> <\/SCRIPT>' + '<SCRIPT src ="' + URL + '"onLoad =" this. ownerdocument. X = 1 "> <\/SCRIPT> '; IFRAME. style. display = "NONE"; head. appendchild (IFRAME); var d = IFRAME. contentdocument; IFRAME. onload = function () {If (D. X = void 0) {removescript (name, node, true);} IFRAME. onload = NULL; // opera cannot be removed when IFRAME is bound to an event. removechild (this) ;}; try {d. write (CODE); D. Close () ;}catch (e) {};// execute and remove all modules or callback functions with dependencies resolvecallbacks () {for (VAR I = 0, OBJ; I <checks. length; I ++) {OBJ = checks [I]; for (VAR name in status) {If (status [name] = 3 & obj. deps ["@" + name]) {Delete obj. deps ["@" + name]; obj. length --; DOM ["@ debug"] & Dom. log (obj. length + "" + name) ;}} if (! OBJ. length) {obj. callback () checks. splice (I --, 1 );}}} /*** generate a Script node temporarily for loading the module * @ Param {string} Name Module name * @ Param {string} URL module path */function appendscript (name, URL) {var node = Doc. createelement ("script"); url = URL | Dom. basepath + "/" + name + ". JS "+ (Dom. debug? "? T = "+ new date:" "); node. charset = "UTF-8"; node. async = true; node. onerror = function () {removescript (name, this, true);} node [Method] = function () {If (Dom. rreadystate. test (this. readystate) {for (VAR I = 0; I <checks. length; I ++) {resolvecallbacks ()} removescript (name, this) ;}} node. src = URL + "? Timestamp = "+ (+ new date); Global. opera & fixoperaerror (name, URL, node); head. insertbefore (node, head. firstchild );} /*** remove the temporarily generated Script node * @ Param {string} Name Module name * @ Param {element} node to load the Script node temporarily generated by this module * @ Param {Boolean} error loading failed */function removescript (name, node, error) {var parent = node. parentnode; If (parent & parent. nodetype = 1) {If (error | status [name] = 1) {Dom. stack ('dom. Log ("fail to load module ['+ name +']") '); Dom. stack (true); // print the error stack} If (node. clearattributes) {node. clearattributes ();} else {node [Method] = node. onerror = NULL;} parent. removechild (node) ;}} mix (DOM, {mix: mix, // bind event (simplified version) bind: Doc. dispatchevent? Function (El, type, FN, phase) {el. addeventlistener (type, FN, phase);}: function (El, type, FN) {el. attachevent ("On" + type, function () {fn. call (El, event) ;}) ;}, Stack: function (FN) {If (fn = true) {While (fn = stack. pop () {fn () ;}} else if (typeof FN === "string") {stack. push (new function (FN);} else if (typeof fn = "function") {stack. push (FN) ;},/ *** <a href = "http://www.cnblogs.com/rubylouvre/ Archive/2011/02/10/1950940 .html "> path of the core module </A> * @ property * @ Type string */basepath :( function (URL, scripts, node) {scripts = Doc. getelementsbytagname ("script"); node = scripts [scripts. length-1] url = node. hasattribute? Node. SRC: node. getattribute ('src', 4); Dom. baseurl = URL; return URL. substr (0, URL. lastindexof ('/');}) (),/*** request module * @ Param {string | array} deps dependency list. If it is a string, separate it with commas, if you want to specify a specific path, please write it into parentheses * @ Param {function} module forward callback * @ Param {function} errback negative callback * @ Param {Boolean} Ready: whether to delay DOM tree Creation to execute the callback function */require: function (deps, callback, errback) {var names = []; (deps + ""). replace (Dom. rword, function (URL, name, Match) {match = URL. Match (rmodule); name = match [1]; If (! Status [name]) {// prevents duplicate node generation and Request status [name] = 1; if (name! = "Ready") {appendscript (name, Match [2]); // load the Javascript file Dom. Stack (errback); // press the error stack} If (! Names ["@" + name]) {// prevents names from "node, oop, node. push (name); names ["@" + name] = 1 ;}}); this. provide (names, callback );}, /*** define module * @ Param {string} Name Module name * @ Param {string} dependlist dependency list * @ Param {function} module itself */define: function (name, deps, callback) {If (typeof deps = "function") {// when processing only two parameters, callback = deps; deps = "";} status [name] = 2; function wrap () {status [name] = 3; // The added Ability Dom namespace object passed in, so other modules can use these new capabilities as soon as possible callback ();} wrap. _ name = Name; // if it is an empty string, replace it with an empty array this. require (deps, wrap) ;},/*** assembly module * @ Param {array} array module list * @ Param {function} callback function */provide: function (names, callback) {checks. unshift ({Name: callback. _ name | "", callback: callback, deps: names, Length: names. length}) ;}});/*** domready Mechanism * @ Param {function} FN callback function * @ Param {Boolean} More add Load the specified module */var ready = Dom. ready = function (FN) {If (ready. list) {ready. list. push (FN) ;}else {fn () ;}; ready. list = []; function fireready () {If (ready. list) {for (VAR I = 0, FN; fn = ready. list [I ++];) FN (); status. ready = 3; Delete ready. list ;}}; function doscrollcheck () {try {Dom. HTML. doscroll ("Left"); fireready () ;}catch (e) {setTimeout (doscrollcheck, 0) ;}; // starts determining page loading if (Doc. ready State = "complete") {fireready ();} else {Dom. BIND (Doc, (Doc. dispatchevent? "Domcontentloaded": "readystatechange"), function () {If (Doc. dispatchevent | Doc. readystate = "complete") {fireready () ;}}); try {// http://bugs.jquery.com/ticket/4787 http://cmc3.cn /// under IE6 if the embedded page is reset to document. domain, access window. frameelement throws an error. // The value var toplevel = Global can be accessed only after multiple try catch attempts. frameelement = NULL;} catch (e) {}; if (Dom. HTML. doscroll & toplevel) {doscrollcheck () ;}} dom.exports({{{}(this,this.doc ument); // Private system variables starting with 2011.7.11 // @ prevent direct calls to/Dom. check to Dom ["@ emitter"] // Dom. change namespace to Dom ["@ name"] // Remove useless Dom. modules // optimize the exports Method

Each module is defined as follows (ensure that the module name and file name are consistent ):

(Function (global, DOC) {var dom = global [escape (Doc. URL. split ("#") [0])]; Dom. define ("class", "Lang", function () {Dom. log ("class module") implements logging into metadata (this,this.doc ument );

Usage:

// The callback function will load the class module and run it after domready. // Http://www.cnblogs.com/rubylouvre/archive/2011/07/12/2104777.html by situ zhengmei Dom. Require ("class, ready", function () {alert (1000 )});

Link: My module Loading System V5

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.