zoukankan      html  css  js  c++  java
  • 自己编写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
  • 相关阅读:
    试试SQLServer 2014的内存优化表
    备份数据库的时候设置 BufferCount 选项不正确导致 out of memory 的情况
    SQLSERVER复制优化之一《改变包大小》
    Tomcat配置域名和虚拟文件夹
    BZOJ 1798 [Ahoi2009]Seq 维护序列seq 线段树
    125 Valid Palindrome
    jquery.lazyload.js实现图片懒载入
    hdu 2176 取石子游戏
    算法练习--十进制 二进制互转
    JavaScript学习10:动态载入脚本和样式
  • 原文地址:https://www.cnblogs.com/hoojo/p/jquery_import_dynamic_script_debug_js.html
Copyright © 2011-2022 走看看