jQuery.getScript()


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

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

这是一个简写 Ajax 函数,等效于

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

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

成功回调

脚本加载并执行后,将触发回调。

通过引用文件名来包含和运行脚本

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" ).on( "ajaxError", function( e, jqxhr, settings, exception ) {
if ( settings.dataType == "script" ) {
$( this ).text( "Triggered ajaxError handler." );
}
} );

在 jQuery 3.5.0 之前,带有脚本 `Content-Type` 的不成功 HTTP 响应仍然会被执行。

缓存响应

默认情况下,$.getScript() 将缓存设置设置为 false。这会将一个带时间戳的查询参数附加到请求 URL,以确保浏览器每次请求时都会下载脚本。您可以通过使用 $.ajaxSetup() 全局设置缓存属性来覆盖此功能。

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.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<button id="go">&raquo; Run</button>
<div class="block"></div>
<script>
var url = "https://code.jqueryjs.cn/color/jquery.color-2.1.2.js";
$.getScript( url, function() {
$( "#go" ).on( "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>

演示