Octopress 加速 - 压缩 html

/

rake generate 生成的 html 文件进行压缩,减少传输消耗,新建 rake 任务如下:

require "html_compressor"
require "parallel"
require "ruby-progressbar"

n_cores = 4

desc "Minify HTML"
task :minify_html, :dir do |t, args|
  args.with_defaults(:dir => "#{public_dir}")
  htmls = Dir.glob("#{args.dir}/**/*.html")
  progressbar = ProgressBar.create(:title => "Minify HTML",
                                   :starting_at => 0,
                                   :total => htmls.size,
                                   :format => '%t, %a |%b%i| %p%')
  compressor = HtmlCompressor::HtmlCompressor.new
  Parallel.map(htmls, :in_threads => n_cores) do |f|
    input = File.read(f)
    output = File.open("#{f}", "w")
    output << compressor.compress(input)
    output.close
    progressbar.increment
  end
end

用到了 3 个 Gem,html_compressor 对 html 文件进行压缩,去除注释、空格等,使用的是著名的 yui_compressor,需要 java 环境支持。parallel 添加并行处理能力。ruby-progressbar 添加进度条显示。

rake deploy 中自动调用:

desc "Default deploy task"
task :deploy do
  # Check if preview posts exist, which should not be published
  if File.exists?(".preview-mode")
    puts "## Found posts in preview mode, regenerating files ..."
    File.delete(".preview-mode")
    Rake::Task[:generate].execute
  end

  # Apply custom tasks
  Rake::Task[:minify_html].execute

  Rake::Task[:copydot].invoke(source_dir, public_dir)
  Rake::Task["#{deploy_default}"].execute
end

Comments