複数のJavaScriptを自動的に一つにまとめてくれるRubyのライブラリ

様々なjavascriptライブラリを使用していると、どうしてもファイル数が増えてしまいますよね。
ファイルが増えるのは良いのですが、それによりページを開くのに時間がかかる場合があります。
できるだけ一つにまとめるのが良いようですね。
そこで複数のJavaScriptをサーバーサイドで一つにまとめてくれるRubyライブラリ「Sprockets」をご紹介します。
HTTPのアクセス数を減らす事にもなるのでサーバーにもクライアントにも優しい対策です。
以下のようなコードで動的に生成できるようです。
secretary = Sprockets::Secretary.new(
:asset_root => "public",
:load_path => ["vendor/sprockets/*/src", "vendor/plugins/*/javascripts"],
:source_files => ["app/javascripts/application.js", "app/javascripts/**/*.js"]
)
# Generate a Sprockets::Concatenation object from the source files
concatenation = secretary.concatenation
# Write the concatenation to disk
concatenation.save_to("public/sprockets.js")
# Install provided assets into the asset root
secretary.install_assets
コマンドラインからも実行可能との事。
$ sprocketize -I app/javascripts \
-I vendor/sprockets/prototype/src \
-I vendor/sprockets/color_picker/src \
--asset-root=public \
app/javascripts/*.js > public/sprockets.js
サーバーの負荷対策をされている方はぜひ導入してみてはいかがでしょうか。
最新情報をお届けします
- Website: http://www.getsprockets.org/
- GitHub: http://github.com/sstephenson/sprockets
