jQuery.getScript()
返回: jqXHR
jQuery.getScript( url [, success ] )
描述:使用一个GET HTTP请求,从服务器上载入一个JavaScript文件,并执行它。
加入于: 1.0
jQuery.getScript( url [, success ] )这是$.ajax()函数的简写,它等同于:
$.ajax({
url: url,
dataType: "script",
success: success
});
该脚本是在全局上下文中执行的,所以它可以引用别的变量,并使用函数。包含的脚本可能会对当前网页产生一些影响。
成功的回调函数
一旦脚本被载入的时候,会引发回调函数,但是并非一定会执行。
通过引用文件名来包含脚本并运行脚本:
$.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()以对出错做点解释处理。
$.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()的出错:
$( "div.log" ).ajaxError(function( e, jqxhr, settings, exception ) {
if ( settings.dataType == "script" ) {
$( this ).text( "Triggered ajaxError handler." );
}
});
缓存响应
默认情况下,$.getScript()会把缓存设置为false。这向请求的URL追加了一个时间戳查询参数,以确保浏览器在每次请求的时候都下载该脚本。你可以使用$.ajaxSetup()方法,通过通过全局地设置缓存属性来覆盖这个功能。
$.ajaxSetup({
cache: true
});
会为替代,你可以定义一个新的方法,使用更灵活的$.ajax()方法。
示例
定义一个$.cachedScript()方法,允许获取一个缓存的脚本:
jQuery.cachedScript = function( url, options ) {
// 允许用户设置除了dataType、cache和url之外的任何选项
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// 使用$.ajax()因为它比$.getScript更灵活
// 返回jqXHR对象,因此我们可以连缀回调函数
return jQuery.ajax( options );
};
// 用法
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
动态载入官方的jQuery颜色动画插件,当新功能载入时,绑定一些颜色动画。
<!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">» 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>
演示结果