1+ require 'json'
2+ require 'open3'
3+
14module CriticalPathCss
25 class CssFetcher
3- require 'phantomjs'
4- require 'critical_path_css/configuration'
5-
6- PENTHOUSE_PATH = "#{ File . dirname ( __FILE__ ) } /../penthouse/penthouse.js"
6+ GEM_ROOT = File . expand_path ( File . join ( '..' , '..' ) , File . dirname ( __FILE__ ) )
77
8- def initialize
9- @config = Configuration . new
8+ def initialize ( config )
9+ @config = config
1010 end
1111
1212 def fetch
@@ -20,15 +20,50 @@ def fetch_route(route)
2020 protected
2121
2222 def css_for_route ( route )
23- url = @config . base_url + route
24-
25- Phantomjs . run (
26- '--ignore-ssl-errors=true' ,
27- '--ssl-protocol=tlsv1' ,
28- PENTHOUSE_PATH ,
29- url ,
30- @config . css_path
31- )
23+ options = {
24+ 'url' => @config . base_url + route ,
25+ 'css' => @config . css_path ,
26+ ## optional params
27+ # viewport dimensions
28+ 'width' => 1300 ,
29+ 'height' => 900 ,
30+ # CSS selectors to always include, e.g.:
31+ 'forceInclude' => [
32+ # '.keepMeEvenIfNotSeenInDom',
33+ # '^\.regexWorksToo'
34+ ] ,
35+ # ms; abort critical CSS generation after this timeout
36+ 'timeout' => 30000 ,
37+ # set to true to throw on CSS errors (will run faster if no errors)
38+ 'strict' => false ,
39+ # characters; strip out inline base64 encoded resources larger than this
40+ 'maxEmbeddedBase64Length' => 1000 ,
41+ # specify which user agent string when loading the page
42+ 'userAgent' => 'Penthouse Critical Path CSS Generator' ,
43+ # ms; render wait timeout before CSS processing starts (default: 100)
44+ 'renderWaitTime' => 100 ,
45+ # set to false to load (external) JS (default: true)
46+ 'blockJSRequests' => true ,
47+ # see `phantomjs --help` for the list of all available options
48+ 'phantomJsOptions' => {
49+ 'ignore-ssl-errors' => true ,
50+ 'ssl-protocol' => 'tlsv1'
51+ } ,
52+ 'customPageHeaders' => {
53+ # use if getting compression errors like 'Data corrupted':
54+ 'Accept-Encoding' => 'identity'
55+ }
56+ } . merge ( @config . penthouse_options )
57+ out , err , st = Dir . chdir ( GEM_ROOT ) do
58+ Open3 . capture3 ( 'node' , 'lib/fetch-css.js' , JSON . dump ( options ) )
59+ end
60+ if !st . exitstatus . zero? || out . empty? && !err . empty?
61+ STDOUT . puts out
62+ STDERR . puts err
63+ raise "Failed to get CSS for route #{ route } \n " \
64+ " with options=#{ options . inspect } "
65+ end
66+ out
3267 end
3368 end
3469end
0 commit comments