RequireJS - 從 CDN 載入 jQuery



jQuery 使用 CDN(內容分發網路)透過呼叫 define() 函式定義 jQuery 外掛的依賴項。

載入 jQuery

define(["jquery", "jquery.load_js1", "jquery.load_js2"], function($) {
   $(function() {
      //code here
   });
});

示例

以下示例使用 CDN 定義 jQuery 外掛的依賴項。建立一個名為 index.html 的 html 檔案,並將以下程式碼放入其中 −

<!DOCTYPE html>
<html>
   <head>
      <title>Load jQuery from a CDN</title>
      <script data-main = "app" src = "lib/require.js"></script>
   </head>
   
   <body>
      <h2>Load jQuery from a CDN</h2>
      <p>Welcome to Tutorialspoint!!!</p>
   </body>
</html>

建立一個名為 app.jsjs 檔案,並在其中新增以下程式碼 −

// you can configure loading modules from the lib directory
requirejs.config ({
   "baseUrl": "lib",
   
   "paths": {
      "app": "../app",
	  
      //loading jquery from CDN
      "jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min"
   }
});

//to start the application, load the main module from app folder
requirejs(["app/main"]);

建立一個名為 app 的資料夾,並從該資料夾載入 main.js 模組 −

define(["jquery", "jquery.load_js1", "jquery.load_js2"], function($) {
   
   //loading the jquery.load_js1.js and jquery.load_js2.js plugins 
   $(function() {
      $('body').load_js1().load_js2();
   });
});

再建立一個名為 lib 的資料夾以儲存 require.js 檔案和其他 js 檔案,如下所示 −

lib/jquery.load_js1.js

define(["jquery"], function($) {
   
   $.fn.load_js1 = function() {
      return this.append('<p>Loading from first js file!</p>');
   };
});

lib/jquery.load_js2.js

define(["jquery"], function($) {
   
   $.fn.load_js2 = function() {
      return this.append('<p>Loading from second js file!</p>');
   };
});

輸出

在瀏覽器中開啟 HTML 檔案;您將收到以下輸出 −

RequireJS Loading from CDN
requirejs_jquery.htm
廣告