为 $.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);
为 $.getScript() 移去自动加的时间 timestamp
jquery.getScript主要用来实现jsonp,浏览器跨域获取数据,使用方法如下
代码如下
$.getScript(url,function(){...});
它暗藏了一个深坑:自动给你的url后面加上上timestamp,比如你请求 http://www.45it.com,实际访问url是 "/?_=1379920176108"
如果你本身对url有特别解析,哪就悲剧了,会浪费很多时间debug,要拒绝这种行为,可以改用 jquery.ajax,用法如下
代码如下
1.$.ajax({
2. url: 'http://m.lutaf.com',
3. dataType: "script",
4. cache:true,
5. success: function(){}
6.});using jQuery.ajax and set cache = ture, you can remove the timestamp property alltogether.
动态加载JS【方法getScript】的改进
代码如下
//定义一个全局script的标记数组,用来标记是否某个script已经下载到本地
var scriptsArray = new Array();
$.cachedScript = function (url, options) {
//循环script标记数组
for (var s in scriptsArray) {
//console.log(scriptsArray[s]);
//如果某个数组已经下载到了本地
if (scriptsArray[s]==url) {
return { //则返回一个对象字面量,其中的done之所以叫做done是为了与下面$.ajax中的done相对应
done: function (method) {
if (typeof method == 'function'){ //如果传入参数为一个方法
method();
}
}
};
}
}
//这里是jquery官方提供类似getScript实现的方法,也就是说getScript其实也就是对ajax方法的一个拓展
options = $.extend(options || {}, {
dataType: "script",
url: url,
cache:true //其实现在这缓存加与不加没多大区别
});
scriptsArray.push(url); //将url地址放入script标记数组中
return $.ajax(options);
};
$(function () {
$('#btn').bind('click', function () {
$.cachedScript('t1.js').done(function () {
alertMe();
});
});
$('#btn2').bind('click', function () {
$.getScript('t1.js').done(function () {
alertMe();
});
});
});
自定义的缓存方法
getScript