jQuery.getScript()

jQuery.getScript( url [, success ] )返回类型:jqXHR

描述:使用HTTP GET请求从服务器载入一个JavaScript文件,然后执行它。

这是一个简写的Ajax函数,它等同于:

1
2
3
4
5
$.ajax({
url: url,
dataType: "script",
success: success
});

此脚本在全局上下文中执行,所以它可以引用于其它变量,并使用jQuery函数。包含的脚本可以对当前网页产生一些影响。

Success回调函数

一旦脚本已经载入,但还没有执行,就引发此回调函数。

可以引用文件名来包含并运行脚本:

1
2
3
4
5
6
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});

处理错误

自从jQuery 1.5以来,你可以使用.fail()来处理错误:

1
2
3
4
5
6
7
$.getScript( "ajax/test.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});

在jQuery 1.5以前,就必须用全局.ajaxError()回调函数事件,以处理$.getScript()错误:

1
2
3
4
5
$( "div.log" ).ajaxError(function( e, jqxhr, settings, exception ) {
if ( settings.dataType == "script" ) {
$( this ).text( "Triggered ajaxError handler." );
}
});

缓存响应

默认情况下,$.getScript()cache设置为false。这会给请求的URL追加一个时间戳查询参数,以确保每次请求时,浏览器都会下载脚本。你可以利用$.ajaxSetup(),通过全局地设置cache属性,来覆盖此功能:

1
2
3
$.ajaxSetup({
cache: true
});

或者,你可以定义一个新方法,使用更灵活的$.ajax()方法。

示例:

定义$.cachedScript()方法以允许获取缓存的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 );
});

动态载入官方的jQuery颜色动画插件,并绑定一些颜色动画,当载入新功能时,出现一次颜色动画。

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getScript demo</title>
<style>
.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id="go">&raquo; Run</button>
<div class="block"></div>
<script>
var url = "https://code.jquery.com/color/jquery.color.js";
$.getScript( url, function() {
$( "#go" ).click(function() {
$( ".block" )
.animate({
backgroundColor: "rgb(255, 180, 180)"
}, 1000 )
.delay( 500 )
.animate({
backgroundColor: "olive"
}, 1000 )
.delay( 500 )
.animate({
backgroundColor: "#00f"
}, 1000 );
});
});
</script>
</body>
</html>

演示: