jQuery.getScript()
使用HTTP请求的GET方式从服务器加载JavaScript文件,然后执行它。
jQuery.getScript(url[,success])
- url。类型: String。一个包含发送请求的URL字符串。
- success。类型: Function(
String script,String textStatus,jqXHR jqXHR)。当请求成功后执行的回调函数。
这是一个Ajax函数的缩写,这相当于:
$.ajax({
url: url,
dataType: "script",
success: success
});
这个脚本在全局环境中执行,所以指向其他变量和运行jQuery函数。被加载的脚本同样作用于当前页面:
Success Callback(成功回调)
一旦脚本已经被加载,将触发回调但不一定执行。
$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");
通过引用这个文件名,脚本被包含进来并执行:
$.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.');
});
Handling Errors(错误处理)
从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." );
});
jQuery1.5之前,不得不使用全局的.ajaxError()回调事件来处理$.getScript()错误:
$( "div.log" ).ajaxError(function (e, jqxhr, settings, exception) {if (settings.dataType=='script') { $(this ).text( "Triggered ajaxError handler." ); } });
Caching Responses(缓存响应)
默认情况下,$.getScript() cache选项被设置为false。这将在请求的URL的查询字符串中追加一个时间戳参数,以确保每次浏览器下载的脚本被重新请求。您可以全局的使用$.ajaxSetup()设置cache(缓存)属性覆盖该功能:
$.ajaxSetup({
cache: true
});
另外,你可以使用更灵活的$.ajax()方法定义一个新的方法
例子
定义了一个$.cachedScript()方法可以获取缓存的脚本:
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 callbacksreturn jQuery.ajax(options); }; // Usage $.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://www.lanmper.cn/static/js/jquery-3.5.0.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>
