Created
December 9, 2016 01:56
-
-
Save fallroot/b727f3f9f8345ae934acf3d6be2481e7 to your computer and use it in GitHub Desktop.
Simple CSS Selector Minifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CHARS = [*'A'..'Z', *'a'..'z'] | |
def index_to_shortcut(number, base = 52) | |
quotient, remainder = number.divmod(base) | |
if quotient.zero? | |
CHARS[remainder] | |
else | |
index_to_shortcut(quotient - 1, base) + CHARS[remainder] | |
end | |
end | |
def log_size(original, minified) | |
original_size = File.size(original) | |
minified_size = File.size(minified) | |
ratio = (100.0 * (original_size - minified_size) / original_size).round(2) | |
puts "#{original}" | |
puts "\t#{(original_size / 1024.0).round(2)}KB ➔ #{(minified_size / 1024.0).round(2)}KB" | |
puts "\t#{ratio}% compressed.\n\n" | |
end | |
def make_map(selectors, shortcuts) | |
contents = '' | |
selectors.each_with_index do |value, index| | |
contents << "#{index + 1}\t#{shortcuts[index]}\t#{value}\n" | |
end | |
File.write('map.txt', contents) | |
end | |
selectors = [] | |
shortcuts = [] | |
html_files = ['lezhin.html'] | |
css_path = File.join('./lezhin_files', '*.css') | |
css_files = Dir.glob(css_path) | |
css_files.each do |filename| | |
simple_css= File.read(filename).gsub(/{[^}]+}/, '{}') | |
candidates = simple_css.scan(/(?<=[#.])[a-z]{1}[a-z0-9\-_]*/i).reject{|selector| selector.size < 3} | |
selectors.concat(candidates) | |
end | |
selectors.uniq!.sort_by!{|x| [-x.length, x]} | |
puts "#{selectors.size} selectors found.\n\n" | |
selectors.each_with_index do |value, index| | |
shortcuts << index_to_shortcut(index) | |
end | |
html_files.each do |filename| | |
contents = File.read(filename) | |
contents.gsub!(/^\s+/, '').gsub!(/\r?\n/, '') | |
selectors.each_with_index do |value, index| | |
contents.gsub!(/(?<!<)#{value}/, shortcuts[index]) | |
end | |
new_filename = filename.gsub(/\.html$/, '.min.html') | |
File.write(new_filename, contents) | |
log_size(filename, new_filename) | |
end | |
css_files.each do |filename| | |
contents = File.read(filename) | |
selectors.each_with_index do |value, index| | |
contents.gsub!(/([#.]{1})#{value}/, '\1' + shortcuts[index]) | |
end | |
new_filename = filename.gsub(/\.css$/, '.min.css') | |
File.write(new_filename, contents) | |
log_size(filename, new_filename) | |
end | |
make_map(selectors, shortcuts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment