Requirejs-jquery-from-cdn

提供:Dev Guides
移動先:案内検索

RequireJS-CDNからjQueryをロードする

jQueryはCDN(Content Delivery Network)を使用して、_define()_関数を呼び出してjQueryプラグインの依存関係を定義します。

jQueryの読み込み

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

次の例では、CDNを使用してjQueryプラグインの依存関係を定義します。 _indexl_という名前の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 finddevguides!!!</p>
   </body>
</html>

_app.js_という名前の js ファイルを作成し、その中に次のコードを追加します-

//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();
   });
});

以下に示すように、require.jsファイルと他のjsファイルを保存する_lib_という名前のフォルダーをもう1つ作成します-

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