Home > Article > Web Front-end > Detailed explanation of the loader principle of JavaScript modular programming
There are many JavaScript loaders in the world, such as sea.js, require.js, yui loader, labJs..., the scope of use of loaders is for some relatively large projects. Personally, if it is It is not necessary for small projects. I have used seaJS and requireJS. I have used requireJS in the project. requireJS is compliant with AMD, and its full name is (Asynchronous Module Definition), which is the asynchronous module loading mechanism. seaJS is a loader that complies with the CMD specification.
AMD specification is dependent on front-loading, CMD standard is dependent on post-loading, and the loader of AMD specification will execute all dependencies in JS in front-loading. CMD is lazy loading. If JS needs this module, it will be loaded. Otherwise, it will not be loaded. The problem caused by the loader (requireJS) that complies with the AMD specification may take a longer time to load for the first time because it loads all dependent JS Download them all at once;
Common sense, jQuery supports the AMD specification and does not support the CMD specification. In other words, if you introduce seaJS and want to use jQuery, you must use alias configuration, or directly configure http ://www.php.cn/ Directly introduced into the page;
//这是jQuery源码的最后几行, jQuery到了1.7才支持模块化; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // http://www.php.cn/ if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); };
For example, we can define a module like this:
//文件所在的路径地址为:http://www.php.cn/:63342/module/script/dir2/1.js define(function() { return "!!!!"; });
We can also define a module like this :
//这个文件的路径为http://www.php.cn/:63342/module/main.js , 而且有一个依赖, 加载器会自动去加载这个依赖, 当依赖加载完毕以后, 会把这个依赖(就是script/dir2/1.js)执行的返回值作为这个函数的参数传进去; require(["script/dir2/1.js"], function(module1) { console.log(module1); }); //实际上会打印出 "!!!!"
Generally speaking, a module can only write one define function. There are two main ways to pass parameters to the define function:
1: Normally it can be a function;
2: It can be a list of array type dependencies, and a function;
If a module writes multiple define, it will cause the module to malfunction, and the module defined first will be overwritten by the module defined later ( Of course, generally we don’t play like that);
You can write multiple require in one module. We can directly understand require as an anonymous define module. There can be multiple require in one define module, and the required ones The module will be cached. This cached variable is usually within the closure, and most of the names are modules or something...;
We implement modular development through loader development. To comply with a standard, a module is standardized as a JS, then we can create several new directories for controller, view, and model, also for better maintenance and decoupling in the future:
Usage method:
//这个模块依赖的四个模块,加载器会分别去加载这四个模块; define(["依赖0","依赖1","依赖2","依赖3"], function(依赖0,依赖1,依赖2,依赖3){ }); //返回一个空对象 define(function(){ return {}; }); //直接把require当作是define来用就好了; require(["依赖0","依赖1","依赖2","依赖3"], function(依赖0,依赖1,依赖2,依赖3) { //执行依赖0; 依赖0(依赖1,依赖2,依赖3); }); //这个加载器define函数和require函数的区别是,define我们可以传个name作为第一参数, 这个参数就是模块的名字, 好吧, 不管这些了.....;
The following is the structure of the loader, because the amount of code is very small, so every function is necessary Yes, in order not to affect the overall situation, put the code inside the anonymous self-executing function:
(function() { 定义一个局部的difine; var define; //我偷偷加了个全局变量,好调试啊; window.modules = { }; //通过一个名字获取绝对路径比如传"xx.js"会变成"http://www.mm.com/"+ baseUrl + "xx.html"; var getUrl = function(src) {}; //动态加载js的模块; var loadScript = function(src) {}; //获取根路径的方法, 一般来说我们可以通过config.baseUrl配置这个路径; var getBasePath = function() {}; //获取当前正在加载的script标签DOM节点; var getCurrentNode = function() {}; //获取当前script标签的绝对src地址; var getCurrentPath = function() {}; //加载define或者require中的依赖, 封装了loadScript方法; var loadDpt = function(module) {}; //这个是主要模块, 完成了加载依赖, 检测依赖等比较重要的逻辑 var checkDps = function() {}; 定义了define这个方法 define = function(deps, fn, name) {}; window.define = define; //require是封装了define的方法, 就是多传了一个参数而已; window.require = function() { //如果是require的话那么模块的名字就是一个不重复的名字,避免和define重名; window.define.apply([], Array.prototype.slice.call(arguments).concat( "module|"+setTimeout(function() {},0) )); }; });
Loader source code implementation (compatible with chrome, FF, IE6 ==>> IE11), IE11 does not have the readyState attribute , and there is no currentScript attribute. It’s a scam. You can’t get the JS path currently being executed, so you have to use a hack;
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script> (function() { var define; window.modules = { }; var getUrl = function(src) { var scriptSrc = ""; //判断URL是否是 // ./或者 // /或者 // 直接是以字符串开头 // 或者是以http://开头; if( src.indexOf("/") === 0 || src.indexOf("./") === 0 ) { scriptSrc = require.config.base + src.replace(/^\//,"").replace(/^\.\//,""); }else if( src.indexOf("http:") === 0 ) { scriptSrc = src; }else if( src.match(/^[a-zA-Z1-9]/) ){ scriptSrc = require.config.base + src; }else if(true) { alert("src错误!"); }; if (scriptSrc.lastIndexOf(".js") === -1) { scriptSrc += ".js"; }; return scriptSrc; }; var loadScript = function(src) { var scriptSrc = getUrl(src); var sc = document.createElement("script"); var head = document.getElementsByTagName("head")[0]; sc.src = scriptSrc; sc.onload = function() { console.log("script tag is load, the url is : " + src); }; head.appendChild( sc ); }; var getBasePath = function() { var src = getCurrentPath(); var index = src.lastIndexOf("/"); return src.substring(0,index+1); }; var getCurrentNode = function() { if(document.currentScript) return document.currentScript; var arrScript = document.getElementsByTagName("script"); var len = arrScript.length; for(var i= 0; i<len; i++) { if(arrScript[i].readyState === "interactive") { return arrScript[i]; }; }; //IE11的特殊处理; var path = getCurrentPath(); for(var i= 0; i<len; i++) { if(path.indexOf(arrScript[i].src)!==-1) { return arrScript[i]; }; }; throw new Error("getCurrentNode error"); }; var getCurrentPath = function() { var repStr = function(str) { return (str || "").replace(/[\&\?]{1}[\w\W]+/g,"") || ""; }; if(document.currentScript) return repStr(document.currentScript.src); //IE11没有了readyState属性, 也没有currentScript属性; // 参考 http://www.php.cn/ var stack try { a.b.c() //强制报错,以便捕获e.stack } catch (e) { //safari的错误对象只有line,sourceId,sourceURL stack = e.stack if (!stack && window.opera) { //opera 9没有e.stack,但有e.Backtrace,但不能直接取得,需要对e对象转字符串进行抽取 stack = (String(e).match(/of linked script \S+/g) || []).join(" ") } } if (stack) { /**e.stack最后一行在所有支持的浏览器大致如下: *chrome23: * at http://www.php.cn/:4:1 *firefox17: *@http://www.php.cn/:4 *opera12:http://www.php.cn/ *@http://www.php.cn/:4 *IE10: * at Global code (http://www.php.cn/:4:1) * //firefox4+ 可以用document.currentScript */ stack = stack.split(/[@ ]/g).pop() //取得最后一行,最后一个空格或@之后的部分 stack = stack[0] === "(" ? stack.slice(1, -1) : stack.replace(/\s/, "") //去掉换行符 return stack.replace(/(:\d+)?:\d+$/i, "") //去掉行号与或许存在的出错字符起始位置 }; //实在不行了就走这里; var node = getCurrentNode(); //IE>=8的直接通过src可以获取,IE67要通过getAttriubte获取src; return repStr(document.querySelector ? node.src : node.getAttribute("src", 4)) || ""; throw new Error("getCurrentPath error!"); }; var loadDpt = function(module) { var dp = ""; for(var p =0; p<module.dps.length; p++) { //获取绝对的地址; var dp = getUrl(module.dps[p]); //如果依赖没有加载就直接加载; if( !modules[dp] ) { loadScript(dp); }; }; }; //主要的模块, 检测所有未加载的模块中未完成了的依赖是否加载完毕,如果加载完毕就加载模块, 如果加载过的话,而且所有依赖的模块加载完毕就执行该模块 //而且此模块的exports为该模块的执行结果; var checkDps = function() { for(var key in modules ) { //初始化该模块需要的参数; var params = []; var module = modules[key]; //加载完毕就什么都不做; if( module.state === "complete" ) { continue; }; if( module.state === "initial" ) { //如果依赖没有加载就加载依赖并且modules没有该module就加载这个模块; loadDpt(module); module.state = "loading"; }; if( module.state === "loading") { //如果这个依赖加载完毕 for(var p =0; p<module.dps.length; p++) { //获取绝对的地址; var dp = getUrl(module.dps[p]); //如果依赖加载完成了, 而且状态为complete;; if( modules[dp] && modules[dp].state === "complete") { params.push( modules[dp].exports ); }; }; //如果依赖全部加载完毕,就执行; if( module.dps.length === params.length ) { if(typeof module.exports === "function"){ module.exports = module.exports.apply(modules,params); module.state = "complete"; //每一次有一个模块加载完毕就重新检测modules,看看是否有未加载完毕的模块需要加载; checkDps(); }; }; }; }; }; //[],fn; fn define = function(deps, fn, name) { if(typeof deps === "function") { fn = deps; deps = [];//我们要把数组清空; }; if( typeof deps !== "object" && typeof fn !== "function") { alert("参数错误") }; var src = getCurrentPath(); //没有依赖, 没有加载该模块就新建一个该模块; if( deps.length===0 ) { modules[ src ] = { name : name || src, src : src, dps : [], exports : (typeof fn === "function")&&fn(), state : "complete" }; return checkDps(); }else{ modules[ src ] = { name : name || src, src : src, dps : deps, exports : fn, state : "initial" }; return checkDps(); } }; window.define = define; window.require = function() { //如果是require的话那么模块的名字就是一个不重复的名字,避免和define重名; window.define.apply([], Array.prototype.slice.call(arguments).concat( "module|"+setTimeout(function() {},0) )); }; require.config = { base : getBasePath() }; require.loadScript = loadScript; var loadDefaultJS = getCurrentNode().getAttribute("data-main"); loadDefaultJS && loadScript(loadDefaultJS); })(); </script> </head> <body> </body> </html>
A loader stolen from Ye Dada. This loader is a bit like the delayed object in jQuery. ($.Deferred) implementation of the related method when($.when);
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script> (function () { //存储已经加载好的模块 var moduleCache = {}; var define = function (deps, callback) { var params = []; var depCount = 0; var i, len, isEmpty = false, modName; //获取当前正在执行的js代码段,这个在onLoad事件之前执行 modName = document.currentScript && document.currentScript.id || 'REQUIRE_MAIN'; //简单实现,这里未做参数检查,只考虑数组的情况 if (deps.length) { for (i = 0, len = deps.length; i < len; i++) { (function (i) { //依赖加一 depCount++; //这块回调很关键 loadMod(deps[i], function (param) { params[i] = param; depCount--; if (depCount == 0) { saveModule(modName, params, callback); } }); })(i); } } else { isEmpty = true; } if (isEmpty) { setTimeout(function () { saveModule(modName, null, callback); }, 0); } }; //考虑最简单逻辑即可 var _getPathUrl = function (modName) { var url = modName; //不严谨 if (url.indexOf('.js') == -1) url = url + '.js'; return url; }; //模块加载 var loadMod = function (modName, callback) { var url = _getPathUrl(modName), fs, mod; //如果该模块已经被加载 if (moduleCache[modName]) { mod = moduleCache[modName]; if (mod.status == 'loaded') { setTimeout(callback(this.params), 0); } else { //如果未到加载状态直接往onLoad插入值,在依赖项加载好后会解除依赖 mod.onload.push(callback); } } else { /* 这里重点说一下Module对象 status代表模块状态 onLoad事实上对应requireJS的事件回调,该模块被引用多少次变化执行多少次回调,通知被依赖项解除依赖 */ mod = moduleCache[modName] = { modName: modName, status: 'loading', export: null, onload: [callback] }; _script = document.createElement('script'); _script.id = modName; _script.type = 'text/javascript'; _script.charset = 'utf-8'; _script.async = true; _script.src = url; //这段代码在这个场景中意义不大,注释了 // _script.onload = function (e) {}; fs = document.getElementsByTagName('script')[0]; fs.parentNode.insertBefore(_script, fs); } }; var saveModule = function (modName, params, callback) { var mod, fn; if (moduleCache.hasOwnProperty(modName)) { mod = moduleCache[modName]; mod.status = 'loaded'; //输出项 mod.export = callback ? callback(params) : null; //解除父类依赖,这里事实上使用事件监听较好 while (fn = mod.onload.shift()) { fn(mod.export); } } else { callback && callback.apply(window, params); } }; window.require = define; window.define = define; })(); </script> </head> <body> </body> </html>
Write a small example of MVC. The code is simple and can be ignored by experts. The directory structure is as follows:
We put all the events in controller/mainController.js,
define(["model/data","view/view0"],function(data, view) { var init = function() { var body = document.getElementsByTagName("body")[0]; var aBtn = document.getElementsByTagName("button"); for(var i=0; i< aBtn.length; i++) { aBtn[i].onclick = (function(i) { return function() { body.appendChild( view.getView(data[i]) ); }; })(i); }; }; return { init : init }; });
put all the data in model/data.js;
define(function() { return [ {name : "qihao"}, {name : "nono"}, {name : "hehe"}, {name : "gege"} ]; })
The JS of the view is placed in the view directory. view0.js is mainly responsible for generating HTML strings or DOM nodes;
define(function() { return { getView : function(data) { var frag = document.createDocumentFragment(); frag.appendChild( document.createTextNode( data.name + " ") ); return frag; } } });
The entrance is app.js, which is the same directory as load.html :
require(["controller/mainController"],function( controller ) { controller.init(); });
load.html This is the main interface:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title></head> <body> <button>0</button> <button>1</button> <button>2</button> <button>3</button> <script src="require.js" data-main="app.js"></script> </body> </html>
The above is the detailed explanation of the loader principle of JavaScript modular programming. For more related content, please pay attention to the PHP Chinese website (www.php .cn)!