今天在使用Kindeditor编辑器异步调用时发现的问题。Kindeditor使用JQ的$.getScript()方法重新载入核心文件创建编辑器。
$.getScript('__PUBLIC__/editor/kindeditor.js', function().......
由于需要多次调用到异步加载创建编辑器。打开FireBug网络面板发现,每次加载时都会重新载入JS文件,而不是直接调用浏览器缓存。
如图所示,这样自然影响到了程序的运行速度,同时也浪费了网站的服务器的流量。原因不用说了,看JS后面的随机数就知道了,这是我们最常用的避免浏览器缓存的办法。但在$.getScript中我们并没有使用任何产生随机数的函数啊。
"Be default, $.getScript() sets the cache setting to false." (
缓存响应:
默认情况下,$.getScript() 将缓存设置成 false。这种情况下,会在请求的 URL 后添加一个时间戳的请求参数,保证每次请求时,浏览器每次都会重新下载脚本。你可以重写这个功能,通过设置 $.ajaxSetup() 的 cache 属性:
$.ajaxSetup({
cache: true
});
代码示例:
$.ajaxSetup({
cache: true
});
$.getScript('__PUBLIC__/editor/kindeditor.js', function() {......})
这回你看到了什么?没有请求了,直接调用浏览器缓存了。
当然,你也可以重写函数来为 $.getScript() 添加缓存开关如下:
// add cache control to getScript method
(function($){
$.getScript = function(url, callback, cache) {
$.ajax({type: 'GET', url: url, success: callback, dataType: 'script', ifModified: true, cache: cache});
};
})(jQuery);你还可以定义一个 $.cachedScript() 方法,允许取得经过缓存的脚本:
jQuery.cachedScript = function(url, options) {
// allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
// Usage 用法
$.cachedScript("ajax/test.js").done(function(script, textStatus) {
console.log( textStatus );
});
【文章参考】:
阅读本文后,您的心情是:
恶心
愤怒
强赞
感动
路过
无聊
雷囧
关注
顶0
踩0