Last active
October 12, 2018 15:36
-
-
Save glebm/6360088 to your computer and use it in GitHub Desktop.
inline web fonts | http://blog.glebm.com/2013/08/28/inline-css-fonts.html
This file contains 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
#!/usr/bin/env ruby | |
require 'base64' | |
require 'open-uri' | |
# file or url | |
def get_css(src) | |
if src.start_with? 'http' | |
src = src.gsub('|', '%7C') | |
STDERR.puts "# GET #{src}" | |
# simulate modern browser to get woff | |
open(src, 'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36").read | |
else | |
STDERR.puts "Read #{src}" | |
File.read(src) | |
end | |
end | |
def inline_urls(css) | |
css.gsub! /url\((.*?)\.(\w+)\)/ do | |
ext = $2 | |
url = "#{$1}.#{$2}" | |
STDERR.puts "# Found #{ext} font: #{url}" | |
mime = { | |
'woff' => 'application/font-woff' | |
}[ext] or raise "need mime type for #{ext}" | |
font_src = get_css(url) | |
base_64 = Base64.strict_encode64(font_src) | |
STDERR.puts "# font #{"was %.1fKB, now %.1fKB" % [font_src.bytesize / 1024.0, base_64.bytesize / 1024.0]}" | |
"url('data:#{mime};base64,#{base_64}')" | |
end | |
end | |
raise "please provide url or path, e.g https://fonts.googleapis.com/css?family=Arimo:400" unless ARGV[0] | |
puts inline_urls(get_css ARGV[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've just written a post on CSS inlining http://blog.glebm.com/2013/08/28/inline-css-fonts.html