Any language in the large-scale application phase, it is necessary to undergo the process of splitting the module. For ease of maintenance and teamwork, the closest dojo to Java is the first to introduce the loader, and the early loaders are synchronized, using document.write and synchronous AJAX requests. Later dojo began to design each of its modular structures in a JSONP way. the module that loads the script node as its principal. This is the current mainstream loader mode .
It is important to mention that Dojo's loader and the inventor of the AMD specification are the James Burke,dojo loader independent of the famous require. This chapter will delve into the mechanics of the loader.
1.AMD specification
AMD is the abbreviation for "Asynchronous module definition", meaning "async module definition". There are two major points of emphasis.
- Asynchronous: Effective to avoid the use of synchronous loading causes the page to feign animation situation.
- module definition: Each module must be written in a certain format. The main interfaces are two, define and require. Define is the approach of the module developer, and require is the method that the module user is concerned about.
The case of the define parameter is define (id?,deps,factory). The first one is the module ID, the second is the dependency list, and the third is the factory method. The first two are optional, if the ID is not defined, it is an anonymous module, the loader can apply some "magic" can let it identify what it called, usually, the module ID is approximately equal to the module in the process of the path (put on the line, performance as a URL). In the development process, a lot of things are not determined, some JavaScript files will be moved to remove, so the anonymous module is a big deal. Deps and factory have an agreement, deps have how many elements, factory has how many of the arguments, position one by one corresponds . The pass-through parameter is the return value of the other module.
function (aaa,bbb) { //code });
Typically, there is an AMD object in define that stores information about the module.
The require parameter is require (Deps,callback) , the first is a dependency list, and the second is a callback. Deps How many elements there are, the callback will have the number of arguments, the situation and define method consistent . Internally, therefore, the Define method calls require to load the dependent module, which is always recursive.
Require (["AAA", "BBB"],function(aaa,bbb) { //Code})
The interface is so simple, but require itself contains many features, such as using "! "To introduce a plug-in mechanism for various configurations through Requirejs.config . The module is just part of the integration, you have to open it, you have to close it, so the position of the merge script is very important in the loader, but the front-end JavaScript does not have this function, Requirejs uses node. js to write a r.js to help you merge .
2. The path where the loader is located
To load a module, we need a URL as the load address, and a script as the loading medium. But the user uses the ID when require, so we need a way to convert the ID to a URL. The idea is simple, the Convention is:
BasePath + module ID + ". js"
Since the browser is parsing the DOM from top to bottom, when the browser parses our JavaScript file (the JavaScript file is the loader), it is sure that the last script tag is added to the DOM tree, so we have this method below.
function Getbasepath () { var nodes = document.getElementsByTagName ("script"); var node = nodes[nodes.length-1]; var src = document.queryselector? Node.src:node.getAttribute ("src", 4); return src;
The above approach satisfies 99% requirements, but we have to dynamically load our loader? In the old version of IE, many conventional methods will fail, in addition to API differences, it itself has a lot of bugs, we can hardly point out what is, in short, to solve, such as the following JavaScript judgment.
document.write (' <script src= ' avalon.js > <\/script> '); document.write (' <script src= ' mass.js > <\/script> '); document.write (' <script src= ' jquery.js > <\/script> ');
Mass.js for our loader, which executes the Getbasepath method, is expected to get http://1.1.1/mass.js, but IE7 does return http://1.1.1/jQuery.js
The readychange attribute is required, and Microsoft has this attribute in document, image, XHR, script, and so on. Used to view load conditions .
functionGetbasepath () {varnodes = document.getElementsByTagName ("Script"); if(Window. VBArray) {//if it is IE for(vari = 0; Nodes node = nodes[i++]; ) { if(Node.readystate = = = "Interactive") { Break; } } } Else{node= Nodes[nodes.length-1]; } varsrc = document.queryselector? Node.src:node.getAttribute ("src", 4); returnsrc; }
This is done, and accessing the DOM is much more expensive than the typical JavaScript code. This allows us to use the Error object.
functionGetbasepath () {Try{A.B.C ()}Catch(e) {if(E.filename) {//FF returnE.filename; } Else if(E.sourceurl) {//Safari returnE.sourceurl; } } varnodes = document.getElementsByTagName ("Script"); if(Window. VBArray) {//Higher performance in reverse lookup for(vari = nodes.length; node; node = nodes[--i];) { if(Node.readystate = = = "Interactive") { Break; } }; } Else{node= Nodes[nodes.length-1]; } varsrc = document.queryselector? Node.src:node.getAttribute ("src", 4); returnsrc; }
In actual use, we want to prevent the cache, this may be with the version number, timestamp, and so on, also to be removed .
url = url.replace (/[?#].*/, ""). Slice (0, Url.lastindexof ("/") + 1);
3.require method
the function of the Require method is that the current dependency list is loaded and the user callback is executed . Therefore, there is a loading process where the entire loading process is subdivided into the following steps:
(1) Take the first ID of the dependency list, and convert it to a URL, either by BasePath + ID + ". js" or by mapping the method directly.
(2) Detect whether this module has been loaded, or is being loaded. So there is an object that keeps all modules loaded, and if a module has never been loaded, it goes into the loading process.
(3) Create a script node, bind Onerror,onload,onredychange and other events to determine whether the load succeeds, and then add SRC and insert the DOM tree. Start Load URL
(4) Constructs the module URL, the dependency list and so on as an object, puts in the detection queue, detects when the above event triggers.
Conversion rules for module IDs: http://wiki.commonjs.org/wiki/Modules/1.1.1
In addition to basepath, we usually use the mapping, that is, the user in advance with a method, the ID and the full URL corresponding to the good, so directly take. In addition, the AMD specification also has shim technology. The purpose of the shim mechanism is to allow JS files that do not conform to the AMD specification to seamlessly cut into our loading system.
Common alias mechanism:
require.config ({ alias:{ ' lang ': ' Http://xxx.com/lang.js ', ' css ': '/http Bbb.com/css.js ' } })
jquery or other plugins, we need the shim mechanism
require.config { alias :{' JQuery ' : { ' http://ahthw.com/jQuery1.1.1.js ', "$" }, ' jquery.tooltips ' : { ' http://ahthw.com/xxx.js ', "$", deps: ["JQuery"]}} );
Below is the source code of require
Window.require = $.require =function(list, factory, parent) {//the dependencies used to detect it are all 2 varDeps = {}, //used to save the return value of a dependent moduleargs = [], //number of modules to installDN = 0, //number of modules that have completed installationCN = 0, id= Parent | | "Callback" + SetTimeOut ("1"); Parent= Parent | | BasePath;//Basepash is the path to the loaderString (list). replace ($.rword,function(EL) {varURL =loadjscss (el,parent)if(URL) {DN++; if(Modules[url] && modules[url].state = = = 2) {cn++; } if(!Deps[url]) {args.push (URL); Deps[url]= "Http://baidu.com"//Go heavy } } }); Modules[id]= {//create an object that records module loading and other informationId:id, Factory:factory, Deps:deps, Args:args, state:1 }; if(DN = = cn) {//If the required installation is equal to the installedFirefactory (ID, args, factory);//installing into the frame}Else{//put it in the Test team and wait for Checkdeps to handle it .loadings.unshift (ID); } checkdeps (); }
Every require, equivalent to the current user callback as a non-loaded anonymous module, ID is randomly generated, callback execution, need to deps all the value of 2
There are three important methods in require ,loadjscss, which is used to convert ID to URL, then call LOADJS,LOADCSS, or call require method again ;Factory, is the execution of user callbacks , our ultimate purpose,checkdeps, detection depends on whether the installation is good , installed on the execution of Firefactory ().
function loadjscss (URL, parent, ret, shim) { //omitted }
The Loadjs and Loadcss methods are relatively pure, but Loadjs will do a dead-chain test.
functionloadjs (URL, callback) {//loading the target module through the script node varnode = doc.createelement ("Script"); Node.classname= Moduleclass;//let Getcurrentscript only handle script nodes with class name ModuleclassNODE[W3C? "onload": "onreadystatechange"] =function () { //Factorys inside the factory function with define method (define (id?,deps?,factory)) varFactory =Factorys.pop (); if(callback) {callback (); } if(Checkfail (node,false, !) ) {Console.log ("Loaded successfully" + NODE.SRC, 7) }; } node.onerror=function() {Checkfail (node,true); }; //before inserting to head the first node, prevent IE6 the head tag from being used before it is closed appendchildNODE.SRC =URL; Head.insertbefore (node, head.firstchild); }
Checkfail is mainly for the development of debugging, there are 3 parameters. Node=>script node,onerror=> is OnError trigger,fuckie=> for legacy IE hack.
The way to do this is, JavaScript from load to execution there is a process, in the interact phase, our JavaScript section can be executed, then we will change the state of the module object to 1, if it is undefined, we can be identified as a dead chain. However, this hack is not valid for JavaScript-defined, because the logic to change state to 1 is performed by the Define method. If the decision is a dead chain, we will remove this node.
functionCheckfail (node, onError, Fuckie) {//more hate ie ah, haha varid = node.src;//detect if the chain is deadNode.onload = Node.onreadystatechange = Node.onerror =NULL ; if(OnError | | (Fuckie &&!)modules[id].state)) {SetTimeOut (function() {Head.removechild (node); }); Console.log ("Load" + ID + "Failure" + onerror + "" + (!modules[id].state), 7); } esle {return true; } }
The Checkdeps method executes once before the user loads the module and after the Script.onload , detects the dependency of the module, and if the module has no dependencies or the state is 2, we call the Firefactory () method
functioncheckdeps () {loop: for(vari = loadings.length; ID; id = loadings[--1]) { varobj = Modules[id], Deps =obj.deps; for(varKeyinchdeps) { if(Hasown.call (Deps, key) && modules[key].state!== 2) { ContinueLoop; } } //If Deps is an empty object or other dependent module state is 2 if(Obj.state!== 2) {Loadings.splice (I,1);//you must remove and then install to prevent the DOM tree from being executed multiple times after IE is built.firefactory (obj.id, Obj.args, obj.factory); Checkdeps ();//If successful, execute again to prevent some modules from not loading well } }; }
Finally to the Firefactory method, its work is to collect the return value of various modules from the modules, execute the factory, complete the installation of the module .
function Firefactory (ID, deps, factory) { for (var i = 0; array = [], D; d = d Eps[i++ Object (Modules[id]), ret = factory.apply (global, array); Module.state = 2; if (ret!== void 0 = ret; return ret; }
4.define method
Define has 3 parameters, the first two is optional, in fact, the ID here is no use, it is to developers to see, it still use the Getcurrentscript method to get the script node path to do id,deps do not fill up an empty array.
In addition,define also to consider the problem of cyclic dependence , such as loading a, to rely on B and C, loading B to rely on a in C, when a and B are cyclic dependent. A and B are not executed until they determine that their Deps key values are 2, otherwise they cannot be executed.
The module loader makes our front-end development more industrialized, easy to maintain and debug. Now the domestic seajs,requirejs,kissy are very good choice.
(End of chapter)
Previous chapter: Chapter II: Seed Module Next Chapter: Fourth Chapter: Language module
Chapter III: Module Loading system (REQUIREJS)