这个插件主要是结合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

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

  1. Vue动态引入JS文件

    引入前请先: npm install jquery 正式代码: //动态引入JS文件 function loadJavaScript(src, callback) {let script_list=$ ...

  2. 运行时动态引入JS文件

    运行时动态引入JS文件(尚在开发环境) 1.添加方法 requireJSFiles export function requireJSFiles (target, pathArr) {return n ...

  3. 动态引入js文件-支持cdn等线上地址

    动态引入cdn js文件,并使用js中的变量常量,亲测有效 原文链接:https://blog.csdn.net/Jie_1997/article/details/112011603 function ...

  4. php动态引入js文件路径问题,JavaScript_动态加载外部css或js文件,原理解析:第一步:使用dom创 - phpStudy...

    原理解析:第一步:使用dom创建 应用:1.提高代码的复用,减少代码量:2.添加一个javascript控制器和 session可以实现动态改变页面样式:3.由于是页面是从上到下依次加载文件的,并且边 ...

  5. JSP页面中引入js文件

    1)引入的js文件出错,  检查方法:将Js的内容写在当前的页面的<script> </script>之间,看是否能够正常运行,如果不能,请核查代码  2) 如果引入的代码在当 ...

  6. html动态加载js方法,动态引入js四种方法总结

    这次给大家带来动态引入js四种方法总结,动态引入js四种方法的注意事项有哪些,下面就是实战案例,一起来看一下. index.html test.jsalert("hello! I am te ...

  7. jQuery Masonry 一个 jQuery动态网格布局的插件

    jQuery Masonry 是一个 jQuery动态网格布局的插件. 每个元素都是漂浮在固定的网格布局上面,就像一枚图钉定在墙上一样. 我们发现以下的15网站使用jQuery Masonry的范例. ...

  8. asp.net后台代码动态添加JS文件和css文件的引用

    首先添加命名空间 using System.Web.UI.HtmlControls; 代码动态添加css文件的引用 HtmlGenericControl myCss = new HtmlGeneric ...

  9. 关于引入 js 文件

    一.说说 script 标签的几个常用属性 async 表示立即下载该 js 文件,但不妨碍页面中的其他操作(只对外部 js 文件有效) defer 表示该 js 文件可以延迟到整个页面被解析并显示之 ...

最新文章

  1. Apache Kafka源码剖析:第5篇 业务API处理
  2. python int函数详解,python int()函数
  3. odciexttableopen 调用出错 error open log_如何在 Spring 异步调用中传递上下文
  4. C语言 | 一维数组
  5. mysql卸载权限不够_Linu下启动MySQL结果显示:env: /etc/init.d/mysql:权限不够怎么解决?...
  6. android 高斯模糊 c,c-如何在不使用任何内置高斯函数的情况下对图像进行高斯模糊处理?...
  7. (12)VHDL组合逻辑
  8. Linux中出现 -bash: unzip: command not found
  9. 我所知道的Javascript
  10. linux搭建博客day5-安装Mysql
  11. springMVC Model ModelMap 和 ModelAndView的区别
  12. [Golang]解决Map的并发性问题:sync.Map
  13. cd linux如何连接wifi,cdlinux万能无线系统使用教程
  14. 田洪川(天轰穿)老师谈.NET学习:将励志和教学结合起来
  15. myeclipse删除jar时出错,无法删除怎么办
  16. 离开一线企业,你算老几?(上)
  17. 基于矩阵分解的协同过滤推荐
  18. 怎么做服务器压力测试?
  19. Monte carlo 求解积分
  20. doe五步法_试验设计DOE的五步曲

热门文章

  1. 浅谈TCP的窗口字段
  2. IT外企那点事[转载]
  3. 30秒的PHP代码片段(2)数学 - Math
  4. [Google Guava] 1.3-常见Object方法
  5. PropertyGrid自定义控件
  6. nginx lua redis 访问频率限制(转)
  7. linux分享一:网络设置
  8. LINQ中的延迟查询特性
  9. Android Studio连接天天模拟器
  10. BIM技术在各阶段应用的软件你知多少?