Octopress 加速 - 合并压缩 js
合并和压缩 js 可以减少浏览器的请求数以及传输消耗,所以新建了一个 Rake 任务用于合并和压缩 js。
require "colorize"
js_for_combine = { 'all.js' => ['modernizr-2.0.js', 'libs/jquery.min.js', 'octopress.js', 'other1.js', 'other2.js', 'other3.js', 'other4.js'],
'404.js' => ['libs/jquery.min.js', 'other.js'] }
desc "Combine and minify js"
task :minify_js do
scripts_dir = "#{source_dir}/javascripts"
js_for_combine.each do |k, v|
if File.exist?("#{scripts_dir}/#{k}")
newer = false
v.each do |j|
if File.mtime("#{scripts_dir}/#{j}") > File.mtime("#{scripts_dir}/#{k}")
puts "## Newer file " + "#{j}".colorize(:blue) + " is found"
newer = true
break
end
end
else
newer = true
end
if newer
puts " Combining and Minify js: " + "#{k}".colorize(:red)
output = File.new("#{scripts_dir}/#{k}", "w")
v.each do |j|
output << File.read("#{scripts_dir}/#{j}")
end
output.close
smap_option = "--source-map /tmp/#{k}.map"
smap_root_option = "--source-map-root http://www.jmlog.com"
system "uglifyjs #{scripts_dir}/#{k} -o #{scripts_dir}/#{k.split('.')[0]}.packed.js #{smap_option} #{smap_root_option} -p 5 -m -c"
end
end
end
colorize
Gem 用于彩色输出。js_for_combine
定义用于合并压缩的 js 组,组中的任一 js 文件比目标文件新,都会触发合并压缩生成新的目标文件。最终生成的 js 是形如 xxx.packed.js
的形式。压缩 js 使用的是比较流行的 uglifyjs
,需要另外安装。
在 rake generate
中自动调用:
desc "Generate jekyll site"
task :generate do
raise "### You haven't set anything up yet. First run `rake install` to set up an Octopress theme." unless File.directory?(source_dir)
puts "## Generating Site with Jekyll"
system "compass compile --css-dir #{source_dir}/stylesheets"
# Apply custom tasks
Rake::Task[:minify_js].execute
system "jekyll build"
end
最后,修改相应模板文件注释掉涉及到的 js 调用代码,改为调用 xxx.packed.js
即可。