jQuery动态加载js脚本文件

jQuery getScript()方法加载JavaScript

 

1
2
3
4
5
jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) {
 /*
  做一些加载完成后需要执行的事情
 */
});

  

1
2
3
4
5
6
7
jQuery.getScript("/path/to/myscript.js")
 .done(function() {
  /* 耶,没有问题,这里可以干点什么 */
 })
 .fail(function() {
  /* 靠,马上执行挽救操作 */
});

  

jquery getScript动态加载JS方法改进

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
//定义一个全局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();
});
});
});
</script>
</head>
<body>
<button id="btn">自定义的缓存方法</button>
<br />
<button id="btn2">getScript</button>
</body>
</html>

  t1.js中代码也就是一个函数 

1
2
3
function alertMe() {
alert('clicked me');
}

  

posted @   sovf  阅读(604)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示