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

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

概述

通過 HTTP GET 請求載入並執行一個 JavaScript 檔案。

jQuery 1.2 版本之前,getScript 只能呼叫同域 JS 檔案。 1.2中,您可以跨域呼叫 JavaScript 檔案。注意:Safari 2 或更早的版本不能在全域性作用域中同步執行指令碼。如果通過 getScript 加入指令碼,請加入延時函式。

參數

url,[callback] String,Function V1.0

url :待載入 JS 檔案地址。

callback :成功載入后回撥函式。

示例

描述:

載入 <a title="//jquery.com/plugins/project/color" class="external text" href="//jquery.com/plugins/project/color">jQuery 官方顏色動畫外掛</a> 成功后繫結顏色變化動畫。

HTML 程式碼:

<button id="go">» Run</button>
<div class="block"></div>
jQuery 程式碼:

jQuery.getScript("//dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: 'pink' }, 1000)
      .animate( { backgroundColor: 'blue' }, 1000);
  });
});

描述:

載入並執行 test.js。

jQuery 程式碼:

$.getScript("test.js");

描述:

載入並執行 test.js ,成功后顯示資訊。

jQuery 程式碼:

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