Skip to content

Instantly share code, notes, and snippets.

@jvanzyl
Last active August 29, 2015 13:55
Show Gist options
  • Save jvanzyl/8762604 to your computer and use it in GitHub Desktop.
Save jvanzyl/8762604 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Before starting:
# gem install deadweight
#
# This is a quick hack to walk through a Jekyll site processing all the CSS files against the site pages to
# get rid of all the unused CSS elements. We used a nice theme but it had tons of crap in it that we'll never
# use and made it very hard to reason about.
#
require 'deadweight'
require 'css_parser'
include CssParser
htmlFiles = []
Dir.glob('*.html').each do |htmlFile|
htmlFiles << "/#{htmlFile}"
end
puts htmlFiles
#
# Use deadweight to find all the un/used selectors so we can eliminate them from our CSS files. This assumes
# you've fired up Jekyll in server mode
#
dw = Deadweight.new
dw.root = "http://localhost:4000"
dw.stylesheets = ["/assets/css/style.css"]
dw.pages = htmlFiles
unused_selectors = dw.run
parser = CssParser::Parser.new
parser.load_file!('assets/css/style.css')
#
# Create a map of declaration as the key and selectors as values so that when a set of
# selectors have the same declaration we can output them in compact form.
#
used_selectors = {}
parser.each_selector do |selector, declarations, specificity|
unless unused_selectors.include? selector
if used_selectors[declarations].nil?
used_selectors[declarations] = selector
else
used_selectors[declarations] = used_selectors[declarations] + ', ' + selector
end
end
end
#
# Just output a crap file and inspect before replacing the target CSS file. Once done this is the nicest
# CSS pretty printer I found: http://www.dirtymarkup.com
#
File.open('foo.css', 'w') { |f|
used_selectors.each do |declarations, selector|
f.write "#{selector} {\n"
f.write " #{declarations}\n"
f.write "}\n"
f.write "\n"
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment