-
Notifications
You must be signed in to change notification settings - Fork 0
/
css-gather.rb
executable file
·49 lines (41 loc) · 987 Bytes
/
css-gather.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'docopt'
require 'nokogiri'
require 'open-uri'
module CssGather
def self.gather_css(url)
critical_css = find_stylesheets(url)
gather_stylesheets(critical_css)
end
def self.find_stylesheets(url)
document = Nokogiri.HTML(URI.parse(url).open)
all_css = document.css('link[rel="stylesheet"],style')
all_css.reject { |s| s['media'] == 'print' }
.reject { |s| s['id'] =~ /criticalCss|cssHide/ }
end
def self.gather_stylesheets(css)
css.map do |stylesheet|
case stylesheet.name
when 'link'
URI.parse(stylesheet['href']).open.read
when 'style'
stylesheet.content
else
die 'Unexpected node type'
end
end.join("\n")
end
end
# docs = <<~DOC
# Fetch CSS
# Usage:
# #{__FILE__} <url>
# DOC
# begin
# opts = Docopt.docopt(docs)
# gather_css opts['<url>']
# rescue Docopt::Exit => e
# puts e.message
# exit 1
# end