首頁  >  ajax  > $.getScript(url,[callback])

返回值:XMLHttpRequestjQuery.getScript(url, [callback])

jQuery $.getScript() 方法概述

通過 HTTP GET 請求載入并執(zhí)行一個(gè) JavaScript 文件。

jQuery 1.2 版本之前,getScript 只能調(diào)用同域 JS 文件。 1.2中,您可以跨域調(diào)用 JavaScript 文件。注意:Safari 2 或更早的版本不能在全局作用域中同步執(zhí)行腳本。如果通過 getScript 加入腳本,請加入延時(shí)函數(shù)。

參數(shù)

url,[callback]String,FunctionV1.0

url:待載入 JS 文件地址。

callback:成功載入后回調(diào)函數(shù)。

示例

描述:

載入 <a title="http://jquery.com/plugins/project/color" class="external text" >jQuery 官方顏色動(dòng)畫插件</a> 成功后綁定顏色變化動(dòng)畫。

HTML 代碼:
<button id="go">» Run</button>
<div class="block"></div>
jQuery 代碼:
jQuery.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);
  });
});

描述:

加載并執(zhí)行 test.js。

jQuery 代碼:
$.getScript("test.js");

描述:

加載并執(zhí)行 test.js ,成功后顯示信息。

jQuery 代碼:
$.getScript("test.js", function(){
  alert("Script loaded and executed.");
});