jQuery.getScript()
jQuery.getScript( url, [ success(data, textStatus) ] ) 返回: XMLHttpRequest
描述: 通過 HTTP GET 請求從服務(wù)器載入并執(zhí)行一個 JavaScript 文件
-
version added: 1.0jQuery.getScript( url, [ success(data, textStatus) ] )
url一個包含發(fā)送請求的URL字符串。
success(data, textStatus)當請求成功后執(zhí)行的回調(diào)函數(shù)。
這是一個快速的AJax處理函數(shù),相當于:
$.ajax({
url: url,
dataType: 'script',
success: success
});
通過返回JavaScript的文件回調(diào)。通常不會有用作為該腳本已經(jīng)執(zhí)行到了這一點。
這個腳本在全局環(huán)境中已經(jīng)執(zhí)行,所以指向其他變量和使用jQuery函數(shù)。包含的腳本必須有一些效果在當前的頁面上:
$('.result').html('<p>Lorem ipsum dolor sit amet.</p>');
通過引用這個文件名,腳本被包含進來并執(zhí)行:
$.getScript('ajax/test.js', function() {
alert('Load was performed.');
});
Examples:
Example: 我們動態(tài)加載新的官方j(luò)Query 顏色動畫插件,一旦該插件加載完成就會觸發(fā)一些顏色動畫。
<!DOCTYPE html>
<html>
<head>
<style>.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}</style>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
<button id="go">» Run</button>
<div class="block"></div>
<script>$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});</script>
</body>
</html>
Demo:
Example: 加載并執(zhí)行test.js文件。
$.getScript("test.js");
Example: 加載并執(zhí)行test.js文件,當執(zhí)行完成就顯示一個警告。
$.getScript("test.js", function(){
alert("Script loaded and executed.");
});