经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
Layui 源码浅读(模块加载原理)
来源:cnblogs  作者:五岁能抬头  时间:2021/3/1 11:20:46  对本文有异议

经典开场

  1. // Layui
  2. ;! function (win) {
  3. var Lay = function () {
  4. this.v = '2.5.5';
  5. };
  6. win.layui = new Lay();
  7. }(window);
  8. // Jquery
  9. (function (global, factory) {
  10. "use strict";
  11. if (typeof module === "object" && typeof module.exports === "object") {
  12. module.exports = global.document ?
  13. factory(global, true) :
  14. function (w) {
  15. if (!w.document) {
  16. throw new Error("jQuery requires a window with a document");
  17. }
  18. return factory(w);
  19. };
  20. } else {
  21. factory(global);
  22. }
  23. })(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
  24. var jQuery = function (selector, context) {
  25. return new jQuery.fn.init(selector, context);
  26. };
  27. return jQuery;
  28. });

这是一种很经典的开场方式,以 ! 定义一个函数并立即执行,并且将对象赋值到全局 window 变量上。当然除了 ! 还有 ~ 等符号都可以定义后面的这个函数,而 ; 应该是为了防止其他的代码对本身造成影响。

实际上( function (window) { "use strict"; } )( window )的写法更被我们理解,如Jquery未压缩的源码。而!定义函数的方法唯一优势就是代码相对较少,所以压缩后的Js代码大多数会以!开头。

动态加载

  1. Lay.prototype.link = function (href, fn, cssname) {
  2. var that = this,
  3. link = doc.createElement('link'),
  4. head = doc.getElementsByTagName('head')[0];
  5. if (typeof fn === 'string')
  6. cssname = fn;
  7. var app = (cssname || href).replace(/\.|\//g, '');
  8. var id = link.id = 'layuicss-' + app,
  9. timeout = 0;
  10. link.rel = 'stylesheet';
  11. link.href = href + (config.debug ? '?v=' + new Date().getTime() : '');
  12. link.media = 'all';
  13. if (!doc.getElementById(id)) {
  14. head.appendChild(link);
  15. }
  16. if (typeof fn != 'function') return that;
  17. (function poll() {
  18. if (++timeout > config.timeout * 1000 / 100) {
  19. return error(href + ' timeout');
  20. };
  21. if (parseInt(that.getStyle(doc.getElementById(id), 'width')) === 1989) {
  22. fn();
  23. } else {
  24. setTimeout(poll, 100);
  25. }
  26. }());
  27. return that;
  28. }

先来看看官方文档:

方法:layui.link(href)
href 即为 css 路径。注意:该方法并非是你使用 layui 所必须的,它一般只是用于动态加载你的外部 CSS 文件。

虽然官方只给出了一个参数,但是我们看源码的话可以知道后两个参数是加载完后运行的函数和自定义的Id。
有趣的是,临时创建的 poll函数 如果parseInt(that.getStyle(doc.getElementById(id), 'width')) === 1989判断为 false ,也就是样式没有被引入的时候会重新调用 poll函数 最后要么加载成功循环结束,要么加载超时调用 Layui hint 打印出超时信息。
因为同样的手段在加载 module 时也同样使用到,所以如果你使用过 Layui 那么[module] is not a valid module这样的警告或多或少能遇到几次。

模块引入

用过 Layui 的兄dei应该对 layui.use 不陌生,先来看官方文档:

方法:layui.use([mods], callback)
layui 的内置模块并非默认就加载的,他必须在你执行该方法后才会加载。

对于用了 Layui 有段时间的我来说,也只是按照官方的例子使用,并不知道实现的原理。
接下来就是见证遗迹的时候,看看 layui.use 做了什么:

  1. Lay.fn.use = function (apps, callback, exports) {
  2. function onScriptLoad(e, url) {
  3. var readyRegExp = navigator.platform === 'PLaySTATION 3' ? /^complete$/ : /^(complete|loaded)$/;
  4. if (e.type === 'load' || (readyRegExp.test((e.currentTarget || e.srcElement).readyState))) {
  5. config.modules[item] = url;
  6. head.removeChild(node);
  7. (function poll() {
  8. if (++timeout > config.timeout * 1000 / 4) {
  9. return error(item + ' is not a valid module');
  10. };
  11. config.status[item] ? onCallback() : setTimeout(poll, 4);
  12. }());
  13. }
  14. }
  15. function onCallback() {
  16. exports.push(layui[item]);
  17. apps.length > 1 ? that.use(apps.slice(1), callback, exports) : (typeof callback === 'function' && callback.apply(layui, exports));
  18. }
  19. var that = this,
  20. dir = config.dir = config.dir ? config.dir : getPath;
  21. var head = doc.getElementsByTagName('head')[0];
  22. apps = typeof apps === 'string' ? [apps] : apps;
  23. if (window.jQuery && jQuery.fn.on) {
  24. that.each(apps, function (index, item) {
  25. if (item === 'jquery') {
  26. apps.splice(index, 1);
  27. }
  28. });
  29. layui.jquery = layui.$ = jQuery;
  30. }
  31. var item = apps[0],
  32. timeout = 0;
  33. exports = exports || [];
  34. config.host = config.host || (dir.match(/\/\/([\s\S]+?)\//) || ['//' + location.host + '/'])[0];
  35. if (apps.length === 0 || (layui['layui.all'] && modules[item]) || (!layui['layui.all'] && layui['layui.mobile'] && modules[item])) {
  36. return onCallback(), that;
  37. }
  38. if (config.modules[item]) {
  39. (function poll() {
  40. if (++timeout > config.timeout * 1000 / 4) {
  41. return error(item + ' is not a valid module');
  42. };
  43. if (typeof config.modules[item] === 'string' && config.status[item]) {
  44. onCallback();
  45. } else {
  46. setTimeout(poll, 4);
  47. }
  48. }());
  49. } else {
  50. var node = doc.createElement('script'),
  51. url = (modules[item] ? dir + 'lay/' : /^\{\/\}/.test(that.modules[item]) ? '' : config.base || '') + (that.modules[item] || item) + '.js';
  52. node.async = true;
  53. node.charset = 'utf-8';
  54. node.src = url + function () {
  55. var version = config.version === true ? config.v || (new Date()).getTime() : config.version || '';
  56. return version ? '?v=' + version : '';
  57. }();
  58. head.appendChild(node);
  59. if (!node.attachEvent || (node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code]') < 0) || isOpera) {
  60. node.addEventListener('load', function () {
  61. onScriptLoad(e, url);
  62. }, false);
  63. } else {
  64. node.addEventListener('onreadystatechange', function (e) {
  65. onScriptLoad(e, url);
  66. });
  67. }
  68. config.modules[item] = url;
  69. }
  70. return that;
  71. };

首先跳过前两个创建的函数,经过一堆巴拉巴拉的赋值后来到第2个if中我们直接可以判断语句apps.length === 0,根据文档可知我们第一个参数是一个数组 [mods] ,当然前面的赋值apps = typeof apps === 'string' ? [apps] : apps;可以看出即使你传的是一个字符串也会被封装成数组。

很明显第一次进来apps.length === 0和下面的if ( config.modules[item] ) 也必为 false ,那么我们直接移步到 else 内。

创建一个 script 元素并赋予属性和模块的地址,通过 appendChild 追加到 head 之后留下一个 addEventListener 监听 script 的加载( ps:attachEvent 是给非人类使用的浏览器准备的 )并将开始创建的 function onScriptLoad(e, url)函数抛进去,然后整段代码除了return that到这里戛然而止。

再来看看function onScriptLoad(e, url)函数,首先开幕雷击 "PLaySTATION 3" === navigator.platform

Layui 的业务已经发展到PS3上了吗?

仅关心PC端浏览器的部分e.type === 'load', 因为监听的是 load 所以这里必为 true 并执行config.modules[item] = url后将追加的 script 元素移除。剩余的代码就是动态加载时使用的技巧,直到 config.status[item]true 时循环结束。

定义模块

由于config.status[item]不会自动变成 true,之后的骚操作由 layui.define 接手。

先看官方文档:

方法:layui.define([mods], callback)

通过该方法可定义一个 layui 模块。参数 mods 是可选的,用于声明该模块所依赖的模块。callback 即为模块加载完毕的回调函数,它返回一个 exports 参数,用于输出该模块的接口。

以比较常用的 laypage.js 模块为例,基础源码如下:

  1. // Laypage 模块的部分代码(部分变量名为猜测,但不影响内容本身)
  2. layui.define(function (exports) {
  3. 'use strict';
  4. var MOD_NAME = 'laypage',
  5. LayPage = function (options) {
  6. var that = this;
  7. that.config = options || {}, that.config.index = ++laypage.index, that.render(true);
  8. };
  9. var laypage = {
  10. render: function (options) {
  11. var laypage = new LayPage(options);
  12. return laypage.index
  13. },
  14. index: layui.laypage ? layui.laypage.index + 10000 : 0,
  15. on: function (elem, even, fn) {
  16. return elem.attachEvent ? elem.attachEvent("on" + even, function (param) {
  17. param.target = param.srcElement, fn.call(elem, param)
  18. }) : elem.addEventListener(even, fn, false), this
  19. }
  20. };
  21. exports(MOD_NAME, laypage);
  22. });

因为 Layui 已经注册了全局的变量,所以当模块文件通过元素追加的方式引入时,调用了 layui.define 方法:

  1. Lay.fn.define = function (deps, callback) {
  2. var that = this,
  3. type = typeof deps === 'function',
  4. mods = function () {
  5. var e = function (app, exports) {
  6. layui[app] = exports;
  7. config.status[app] = true;
  8. }
  9. typeof callback === 'function' && callback(function (app, exports) {
  10. e(app, exports);
  11. config.callback[app] = function () {
  12. callback(e);
  13. }
  14. });
  15. return this;
  16. };
  17. type && (callback = deps, deps = []);
  18. if (!layui['layui.all'] && layui['layui.mobile']) {
  19. return mods.call(that);
  20. } else {
  21. that.use(deps, mods);
  22. return that;
  23. }
  24. };

因为不管你在定义的模块中有没有引入其他模块,如 laypage 和 laytpl 这些 Layui 本身提供的模块都会因 (callback = deps, deps = []) 回到 [mods], callback 的参数格式。

再经过一系列巴拉巴拉的步骤回到定义的 mods 方法中,由layui[app] = exports, config.status[app] = true给全局 layui 变量添加属性(app)且给属性赋值(exports),并把 status 改为 true 至此模块加载完成。

总结

正如 Layui 官方所说:我们认为,这恰是符合当下国内绝大多数程序员从旧时代过渡到未来新标准的最佳指引

作为一个后端的工作者(以后可能要接触前端框架的人)没有接触过前端框架,只对原生态的 HTML / CSS / JavaScript 有所了解,那么 Layui 无非是较优的选择。

而写这篇文章无非就是为了感谢 Layui 对非前端工作者做出的贡献,也可能是我对使用了两年多 Layui 最后的告别吧,感谢贤心。

相关网站

其他

如果你没有接触过 UglifyJS 或其他 JS 压缩器,而你又恰巧使用 Visual Studio Code 工具开发,那么 Minify 扩展插件就已经足够日常使用了。

原文链接:http://www.cnblogs.com/carelessboy/p/14462151.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号