如何使用 jQuery.getScript() 方法載入外部 JavaScript 檔案?


jQuery.getScript( url, [callback] ) 方法使用 HTTP GET 請求載入和執行 JavaScript 檔案。

以下是該方法使用到的所有引數的說明 −

  • url − 一個包含傳送請求的 URL 的字串
  • callback − 此可選引數表示在成功載入資料時執行的函式。

假設我們在result.js 檔案中擁有以下 JavaScript 內容 −

function CheckJS(){
   alert("This is JavaScript");
}

示例

以下是顯示如何使用此方法的程式碼片段 −

<head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               $.getScript('result.js', function(jd) {
                  // Call custom function defined in script
                  CheckJS();
               });
            });
               
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.js file −</p>
       
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>

更新日期:2020-02-17

3K+ 瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.