複数のファイルを持つことは確かに物事を整理するのに役立ちますが、同時にブラウザがサーバーに複数のリクエストを行う必要があり、サイトの読み込み時間に影響を与える可能性があります.
これが、多くの人が最近RequireJSなどのツールを使用する理由です。
簡単に言えば、必要な数の小さなモジュールを (それぞれ別のファイルで) 定義できるようにし、それらを非同期的にロードします。
Grunt などのビルド ツールと組み合わせると、2 つのファイル (RequireJS ライブラリと JS ファイル、つまりmain.js
)のみをロードする Web ページを作成できますmain.js
が、多くの小さなモジュールを連結した結果になります。
このようにして、リクエストの数を最小限に抑えると同時に、コードを整理して小さなモジュールに分割します コストは?追加のビルド ステップを導入します。ただし、このビルド手順は、 などのツールを使用してさらに自動化できますgrunt-contrib-watch
。
main.js
以下は、1 つのファイルを使用し、Google CDN から読み込まれる jQuery に依存するサイトのスニペットです。
まず、main.js : これは RequireJS モジュール (AMD モジュール) であり、次のようになります。
// Tell RequireJS that jQuery dependency should be loaded from the given URL.
// Without this, RequireJS would try to find jQuery.js file locally.
requirejs.config({
paths: {
'jQuery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min',
},
shim: {
'jQuery': {'exports': 'jQuery'},
}
});
// You define that the module below depends on jQuery and two custom modules.
define(['jQuery', 'module1', 'module2'], function ($, Module1, Module2) {
// Here you can access $, Module1 and Module2
});
次に、Grunt のgrunt-contrib-requirejs
プラグインを ( Gruntfile.js )のような構成で使用します。
requirejs: {
compile: {
options: {
baseUrl: 'src/js', // modules dir, which contains main.js, module1.js etc.
out: 'static/js/main.js', // output file
name: 'main',
paths: {
'jQuery': 'http://lorem.ipsum1' // jQuery will be loaded separately from CDN
},
optimize: 'uglify2' // minify output file
}
}
}
最後に、RequireJS スクリプトをロードし、main.js
ファイルをサイトのエントリ ポイント ( index.html )として使用するように指示します。
<script src="js/require.min.js" data-main="js/main.js"></script>