項目裡 CSS 與 JS 文件數量偏多,而 Rails 3.0 尚未自帶 asset pipeline,這會直接拖累加載速度。以我們的布局頁 origin.html.erb 為例:19 個 JS、15 個 CSS,每次打開要發送 34 個請求,體驗顯然不可接受。目標很明確——把這些文件分別合併壓縮成一個。
require File.expand_path('../config/application', __FILE__)
require 'rake'
include Rake::DSL # 新增這一行,注意位置
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
module Commands; end # 新增這一行,注意位置
require 'rails/commands'
$ bundle exec rails plugin install git://github.com/sbecker/asset_packager.git
把用到的 JS、CSS 按分組寫進配置:
---
javascripts:
- base:
- jquery-1.9.1.min
- bootstrap.min
- jquery-migrate-1.1.1
- jquery-ui-1.10.1.custom.min
- jquery-ujs-for-jquery-1.9
- jquery.treeview
- jquery.toastmessage
- jquery-autocomplete-combobox
- jquery.uploadify
- jquery-ui-timepicker-addon
- jquery.ui.datepicker-zh-CN
- select2
- select2_locale_zh-CN
- global
- jquery.tagit
- jquery.validate
- jqueryui-editable
- jquery.ui.widget
stylesheets:
- base:
- style
- invalid
- reset
- jquery.treeview
- jquery-ui-1.10.1.custom
- jquery.toastmessage
- jquery-autocomplete-combobox
- uploadify
- select2
- jquery.tagit
- jquery.validate
- cms
- jqueryui-editable
- bootstrap.min
- customized_bootstrap
<%= raw stylesheet_link_merged :base %> <%= raw javascript_include_merged :base %>
忽略生成的合併文件:
public/javascripts/base_packaged.js public/stylesheets/base_packaged.css
壓縮後的 JS 在 Firefox 下工作異常。為了穩妥,最終只保留合併、跳過壓縮。修改插件源碼:
# vim vendor/plugins/asset_packager/lib/synthesis/asset_package.rb
128 def create_new_build
133 #File.open(new_build_path, "w") {|f| f.write(compressed_file) }
134 File.open(new_build_path, "w") {|f| f.write( merged_file ) }
137 end
把寫入內容從 compressed_file 換成 merged_file 即可。
若發現某個合併文件是空白,刪掉它再刷新頁面:
$ rm public/javascripts/base_packaged.js public/stylesheets/base_packaged.css
刷新後新的合併文件會重新生成。
更多用法可參考項目主頁:https://github.com/sbecker/asset_packager 。在 asset pipeline 尚未普及的 Rails 3 時代,這套方案能直接把請求數從幾十降到個位數,收益非常直觀。