自己編寫jQuery動態引入js文件插件 (jquery.import.dynamic.script)


這個插件主要是結合jquery或者xhr異步請求來使用的,它可以把已經引入過的js文件記錄在瀏覽器內存中,當下次再引入相同的文件就忽略該文件的引入。

 

當你用$.load("dir/my-page.jsp"); 或xhr.request("server/to-my-page");等異步請求加載html頁面的時候,在頁面中導入js文件用本插件進行引入的話,

那么其他請求的頁面中也導入了和前面頁面相當的js文件的情況下,那這些js文件就不需要重新引入。插件會自動忽略之前已經引入過的文件,來節約開銷加快速度。

 

此插件不支持瀏覽器刷新保存數據,那需要利用cookie來保存引入數據記錄。這里只時候異步加載js文件的方式。

 

 

使用本插件必須先引入jquery,后再引入動態導入插件js文件。在不刷新頁面的情況下,本插件導入的javascript只需用導入一次,后面都會使用上一次導入的緩存文件

下面簡單說下插件用法,使用規則方法:

 

1、導入一個文件

1 // 導入一個文件
2 $.imports("${pageContext.request.contextPath }/statics/js/jquery.json/jquery.json.js");
3 //src=導入文件;delay=延遲200毫秒導入;參數once=表示每次都導入,忽略上次導入(大部分情況不需要設置)
4 $.imports({ src: "${pageContext.request.contextPath }/statics/js/jquery.json/jquery.json.js", delay: 200, once: false });

 

 

2、導入多個文件

1 // 導入多個文件
2 $.imports("dir/jquery.json.js", "dir/jquery.json2.js", ".....");
3 $.imports(["dir/jquery.json.js", "dir/jquery.json2.js", "....."]);
 1 導入多個js文件,額外加些配置
 2 $.imports([
 3     { src: "${pageContext.request.contextPath }/statics/js/jquery.json/jquery.json.js", delay: 200, once: false },
 4     { src: "${pageContext.request.contextPath }/statics/js/jquery.json/jquery.json.js", delay: 200 }
 5 ]);
 6 
 7 $.imports(
 8     "${ctxPath }/statics/js/jquery.raty.min.js",
 9      { src: "${ctxPath }/statics/js/student/appraise.js", once: false }
10 );

 

 

3、導入js文件完成后,執行回調函數

1 //支持回調,有回調函數的將使用同步導入。就是前面的javascript都會按順序導入
2 $.imports("dir/jquery.json.js", "dir/jquery.json2.js", ".....", function () {
3     //call back
4 });

 

 

4、全部完整配置參數列表

 1 //完整參數
 2 $.imports({
 3     // 根路徑    
 4     rootPath: ctxPath,
 5     scripts: [ {
 6         src: "js/1.js", // js路徑
 7         delay: 10, // 延遲加載時間
 8         once: true // 是否導入一次,默認ture
 9     }, {
10         path: "js/2.js", // js路徑
11         once: false // 是否導入一次,默認ture
12     } ],
13     // 全局延遲
14     delay: 100,
15     // 回調函數,如果需要的話。使用回調函數將進入同步模式
16     callback: function () {
17         //導入完成執行
18     },
19     // 是否開啟緩存,默認開啟
20     cache: true,
21     // 開啟日志模式
22     debug: false
23 });

上面的同步模式是指js文件的引入順序就是加載的順序,因為有時候后面引入的js依賴前面的就是文件。如果不同步會有找不到變量、方法的問題。當然同步會影響性能,那沒得說的。

 

 

 

廬山真面目,插件源碼在此:

  1 /***
  2  * jquery.import.dynamic.script-debug.js plugin 
  3  * v1.1 
  4  * @createDate -- 2015-08-04
  5  * @author hoojo
  6  * @email hoojo_@126.com
  7  * @requires jQuery v1.8.3 or later
  8  * Copyright (c) 2015 M. hoojo
  9  * Dual licensed under the MIT and GPL licenses:
 10  * http://blog.csdn.net/IBM_hoojo
 11  **/
 12 ;(function ($) {
 13     
 14     var defaultOptions = {
 15         // 根路徑    
 16         rootPath: (function () {
 17             var path = ctxPath || window.location.host + "/eduyun/";
 18             return path;
 19         })(),
 20         scripts: [ {
 21             path: "", // js路徑
 22             src: "", // js路徑
 23             delay: 0, // 延遲加載時間
 24             once: true // 是否導入一次,默認ture
 25         } ],
 26         // 導入過的歷史記錄值棧
 27         importStack: {}, 
 28         // 全局延遲
 29         delay: 0,
 30         // 回調函數,如果需要的話。使用回調函數將進入同步模式
 31         callback: null,
 32         // 是否開啟緩存,默認開啟
 33         cache: false,
 34         // 開啟日志模式
 35         debug: false,
 36         log: function (msg) {
 37             if (defaultOptions.debug) {
 38                 console.log(msg);
 39             }
 40         }
 41     };
 42     
 43     var _options = defaultOptions;
 44     _options.scripts = new Array();
 45     
 46     // 動態導入JavaScript核心代碼
 47     var importScript = function (settings, scripts, call) {
 48         
 49         var item = scripts.shift();
 50 
 51         if ($.type(item) === "string") {
 52             item = { path: item, once: true };
 53         } else if ($.type(item) === "object") {
 54         } else {
 55             throw new Error("unknow params type!");
 56         }
 57         
 58         var script = item.path || item.src;
 59         var delay = item.delay || _options.delay;
 60         var once = item.once === undefined ? true : item.once;
 61         
 62         if (script) {
 63             if (!~script.indexOf(_options.rootPath) && !~script.indexOf("http://")) {
 64                 script =  _options.rootPath + script;
 65             }
 66             
 67             _options.log("================= import stack value ===================");
 68             _options.log(_options.importStack);
 69             
 70             if (!_options.importStack[script] || !once) {
 71                 
 72                 window.setTimeout(function () {
 73                     if (!$("scripts").get(0)) {
 74                         $("body:first").append("<scripts/>");
 75                     }
 76                     
 77                     if (call) {
 78                         _options.log("synchronize import script :" + script + ", delay import script: " + delay);
 79                         
 80                         $.ajax({
 81                             url: script,
 82                             dataType: "script",
 83                             cache: settings.cache || _options.cache,
 84                             async: true,
 85                             success: function () {
 86                                 $("scripts").append('<import src="' + script + '"/>');
 87                                 _options.importStack[script] = true;
 88                                 if (scripts.length == 0) {
 89                                     return call();
 90                                 } else {
 91                                     importScript(settings, scripts, call);
 92                                 }
 93                             }
 94                         });
 95                     } else {
 96                         _options.log("asynchronous import script :" + script + ", delay import script: " + delay);
 97                         //$("scripts").append('<script src="' + script + '" type="text/javascript" charset="utf-8"></script> <import src="' + script + '"/>');
 98                         $.ajax({
 99                             url: script,
100                             dataType: "script",
101                             cache: settings.cache || _options.cache,
102                             async: true,
103                             success: function () {
104                                 $("scripts").append('<import src="' + script + '"/>');
105                                 _options.importStack[script] = true;
106                             }
107                         });
108                         
109                         if (scripts.length == 0) {
110                             return;
111                         } else {
112                             importScript(settings, scripts, null);
113                         }
114                     }
115                     
116                 }, delay);
117             } else {
118                 _options.log("exists script :" + script);
119                 if (scripts.length == 0) {
120                     if (call) return call();
121                 } else {
122                     importScript(settings, scripts, call);
123                 }
124             }
125         }
126     };
127     
128     var mergeScripts = function (args) {
129         var scripts = [];
130         for (var i = 0; i < args.length; i++) {
131             if ($.type(args[i]) === "array") {
132                 scripts = scripts.concat(args[i]);
133             } else {
134                 scripts.push(args[i]);
135             }
136         }
137         
138         return scripts;
139     };
140     
141     // 提供jquery 插件方法
142     $.extend({
143         imports: function (opts) {
144             
145             _options.log("=================== opts ===================");
146             _options.log(opts);
147             _options.log("=================== _options ===================");
148             _options.log(_options);
149             
150             var settings = {};
151             if (arguments.length <= 1) {
152                 var _type = $.type(opts);
153                 if (_type === "string") {
154                     $.extend(settings, _options);
155                     settings.scripts.push(opts);
156                 } else if (_type === "object") {
157                     if (opts.scripts) {
158                         $.extend(settings, _options, opts);
159                     } else {
160                         $.extend(settings, _options);
161                         settings.scripts.push(opts);
162                     }
163                 } else if (_type === "array") {
164                     $.extend(settings, _options, { scripts: opts });
165                 } else {
166                     throw new Error("unknow data type!");
167                 }
168             } else {
169                 var args = Array.prototype.slice.call(arguments); 
170                 if ($.type(args[args.length - 1]) === "function") {
171                     var call = args.pop();
172                     var scripts = mergeScripts(args);
173                     $.extend(settings, _options, { scripts: scripts });
174                     settings.callback = call;
175                 } else {
176                     var scripts = mergeScripts(args);
177                     $.extend(settings, _options, { scripts: scripts });
178                 }
179             }
180             
181             _options.log("=================== settings ===================");
182             _options.log(settings);
183             _options.log("=================== _options ===================");
184             _options.log(_options);
185             
186             importScript(settings, settings.scripts, settings.callback);
187         }
188     });
189     
190 })(jQuery);
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM