淺談js模塊加載方式(初級)

 1.簡介:  前端模塊化開發日漸鼎盛,如何將零散的插件或者是普通的js腳本文件統一管理及引用,是衆多開發者共同的目標。本人是從事.net開發的,最近對前端的一些東西特別的感興趣,也會嘗試的夾雜一點本身的想法,寫一些小東西。東西不牛逼,可是感受用起來仍是方便那麼一點的。下面就展現一下簡短的小代碼。css

 2.中心思想:經過外部調用事先封裝好的模塊加載方法,傳入參數(包括主目錄及模塊js或者css的目錄 ),在程序運行的同時,會動態的將相應的css或者是js代碼追加引用到head標籤內,這樣,就可使用被引用的文件的樣式或者方法啦。前端

 1 (function(req) {
 2     window._Req= req;
 3 })((function($) {
 4     var _factory = function() {}; //模塊工廠
 5     //docker
 6     _factory.prototype = {
 7         _origin: location.origin || location.protocol + "//" + location.host,//域名地址
 8         _aim: null,
 9         _config: function(param) {
10             var _default = { //默認參數
11                     _coreDir: "",
12                     _moduleArr: [
13                         ['', '']
14                     ], //模塊數組
15                 },
16                 _opt = {};
17             $.extend(_opt, _default);
18             if (typeof param === 'object')
19                 $.extend(_opt, param);
20             this._aim = _opt;
21             this._load();   //加載模塊
22         },
23         _load: function() {
24             try {
25                 var _modules = this._aim._moduleArr,
26                     _core = this._aim._coreDir;
27                 _modules.forEach(function(_element) {
28                     _element.forEach(function(_ele) {
29                         var _index = _ele.lastIndexOf('.'), 
30                             _moduleType = _ele.substring(_index + 1), 
31                             _moduleDir = _core + '/' + _ele, 
32                             _module = null;
33                         switch (_moduleType) {
34                             case 'js':
35                                 _module = document.createElement('script');
36                                 _module.src = _moduleDir;
37                                 break;
38                             case 'css':
39                                 _module = document.createElement('link');
40                                 _module.href = _moduleDir;
41                                 _module.rel = 'stylesheet';
42                                 break;
43                             default:
44                                 console.error("對不起模塊類型不匹配");
45                                 break;
46                         }
47                         document.head.appendChild(_module); 
48                     });
49                 }, this);
50             } catch (ex) {
51                 throw ex;
52             }
53         }
54     };
55     return new _factory(); //返回工廠
56 })(jQuery))
源文件
1  _Req._config({
2        _coreDir: "../jq-package",
3                     _moduleArr: [
4                         ['js/ui-dialog.js', 'css/dialog.css']
5                     ], //模塊數組
6   });
調用
相關文章
相關標籤/搜索