自己编写jQuery动态引入js文件插件 (jquery.import.dynamic.script)

栏目: jQuery · 发布时间: 6年前

内容简介:自己编写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         if ($.type(item) === "string") {
 51             item = { path: item, once: true };
 52         } else if ($.type(item) === "object") {
 53         } else {
 54             throw new Error("unknow params type!");
 55         }
 56         
 57         var script = item.path || item.src;
 58         var delay = item.delay || _options.delay;
 59         var once = item.once === undefined ? true : item.once;
 60         
 61         if (script) {
 62             if (!~script.indexOf(_options.rootPath) && !~script.indexOf("http://")) {
 63                 script =  _options.rootPath + script;
 64             }
 65             
 66             _options.log("================= import stack value ===================");
 67             _options.log(_options.importStack);
 68             
 69             if (!_options.importStack[script] || !once) {
 70                 
 71                 window.setTimeout(function () {
 72                     if (!$("scripts").get(0)) {
 73                         $("body:first").append("<scripts/>");
 74                     }
 75                     
 76                     if (call) {
 77                         _options.log("synchronize import script :" + script + ", delay import script: " + delay);
 78                         
 79                         $.ajax({
 80                             url: script,
 81                             dataType: "script",
 82                             cache: settings.cache || _options.cache,
 83                             async: true,
 84                             success: function () {
 85                                 $("scripts").append('<import src="' + script + '"/>');
 86                                 _options.importStack[script] = true;
 87                                 if (scripts.length == 0) {
 88                                     return call();
 89                                 } else {
 90                                     importScript(settings, scripts, call);
 91                                 }
 92                             }
 93                         });
 94                     } else {
 95                         _options.log("asynchronous import script :" + script + ", delay import script: " + delay);
 96                         //$("scripts").append('<script src="' + script + '" type="text/javascript" charset="utf-8"></script> <import src="' + script + '"/>');
 97                         $.ajax({
 98                             url: script,
 99                             dataType: "script",
100                             cache: settings.cache || _options.cache,
101                             async: true,
102                             success: function () {
103                                 $("scripts").append('<import src="' + script + '"/>');
104                                 _options.importStack[script] = true;
105                             }
106                         });
107                         
108                         if (scripts.length == 0) {
109                             return;
110                         } else {
111                             importScript(settings, scripts, null);
112                         }
113                     }
114                     
115                 }, delay);
116             } else {
117                 _options.log("exists script :" + script);
118                 if (scripts.length == 0) {
119                     if (call) return call();
120                 } else {
121                     importScript(settings, scripts, call);
122                 }
123             }
124         }
125     };
126     
127     // 提供jquery 插件方法
128     $.extend({
129         imports: function (opts) {
130             
131             _options.log("=================== opts ===================");
132             _options.log(opts);
133             _options.log("=================== _options ===================");
134             _options.log(_options);
135             
136             var settings = {};
137             if (arguments.length <= 1) {
138                 var _type = $.type(opts);
139                 if (_type === "string") {
140                     $.extend(settings, _options);
141                     settings.scripts.push(opts);
142                 } else if (_type === "object") {
143                     if (opts.scripts) {
144                         $.extend(settings, _options, opts);
145                     } else {
146                         $.extend(settings, _options);
147                         settings.scripts.push(opts);
148                     }
149                 } else if (_type === "array") {
150                     $.extend(settings, _options, { scripts: opts });
151                 } else {
152                     throw new Error("unknow data type!");
153                 }
154             } else {
155                 var args = Array.prototype.slice.call(arguments); 
156                 if ($.type(args[args.length - 1]) === "function") {
157                     var call = args.pop();
158                     $.extend(settings, _options, { scripts: args });
159                     settings.callback = call;
160                 } else {
161                     $.extend(settings, _options, { scripts: args });
162                 }
163             }
164             
165             _options.log("=================== settings ===================");
166             _options.log(settings);
167             _options.log("=================== _options ===================");
168             _options.log(_options);
169             
170             importScript(settings, settings.scripts, settings.callback);
171         }
172     });
173     
174 })(jQuery);

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

重构(影印版)

重构(影印版)

Martin Fowler / 中国电力出版社 / 2003-7-1 / 49.00元

随着对象技术应用越来越普及,软件开发社区出现了一个新的问题。缺乏经验的开发者编写出了大批设计较差的程序,导致这些应用程序非常低效,且难于维护和扩展。本书除了讨论重构的各种技巧之外,还提供了超过70个可行重构的详细编目,对如何应用它们给出了有用的提示;并以step by step的形式给出了应用每一种重构的指南;而且用实例展示了重构的工作原理。这些示例都是用Java语言写成的,但其中的思想却可以运用......一起来看看 《重构(影印版)》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试