rails_critical_css_server 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: c4cd2623f5163950279fbc582ad3911a2a8604b1
4
+ data.tar.gz: d36a67e8ef3581e04ee0d6d17a41b16aeea872b2
5
+ SHA512:
6
+ metadata.gz: fa61e597e5d44d5e20a566cfb2dabd54613fe9218c7b5e9403809d8e2d4bb95b3abc0dda0b97740ccc87310000d223f2b497ec17c0980e4fcacf585320f84180
7
+ data.tar.gz: cfc51bd5a8dd02dad385c94e24d2382b86a7c314cbee94aec28901551cfed7d56cc5092017a3dc5dc55f3b68427e825523452aa24b358e72b1e88332e6510aee
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2017 Michael Wheeler
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # RailsCriticalCssServer
2
+ ## Eliminate render-blocking CSS in above-the-fold content in your Rails app
3
+ If you've run [Google Pagespeed Insights](https://developers.google.com/speed/pagespeed/insights/) on your web app, you might have seen this message:
4
+
5
+ > *Eliminate render-blocking JavaScript and CSS in above-the-fold content*
6
+ >
7
+ > Your page has blocking CSS resources. This causes a delay in rendering your page.
8
+ > None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.
9
+
10
+ This is a Ruby on Rails client for [Critical CSS Server](https://github.com/wheeyls/critical-css-server), designed to solve this problem for you outside of your build process.
11
+
12
+ ## Installation
13
+ Add this line to your application's Gemfile:
14
+
15
+ ```ruby
16
+ gem 'rails_critical_css_server'
17
+ ```
18
+
19
+ And then execute:
20
+ ```bash
21
+ $ bundle
22
+ ```
23
+
24
+ Or install it yourself as:
25
+ ```bash
26
+ $ gem install rails_critical_css_server
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ In your application layout, just wrap your CSS in a call to `Rewrite`:
32
+
33
+ <%= RailsCriticalCssServer::Rewrite.call self do %>
34
+ <%= stylesheet_link_tag "application" %>
35
+ <% end %>
36
+
37
+ Every time a new controller action is rendered, the server will begin to compile the bare-minimum CSS required to
38
+ render the above the fold content on that page. Eventually, once the CSS is available, the critical portion will
39
+ be injected, and the remainder of your CSS will be lazy-loaded with JavaScript.
40
+
41
+ #### Before CSS is ready:
42
+
43
+ The header will be rendered normally:
44
+
45
+ <link rel="stylesheet" href="/assets/application.css" />
46
+
47
+ #### After CSS is compiled:
48
+
49
+ <style>/* inline css rules injected here... */</style>
50
+ <script>// loadCSS injected here...</script>
51
+ <script>loadCSS("/assets/application.css");</script>
52
+ <noscript>
53
+ <link rel="stylesheet" href="/assets/application.css" />
54
+ </noscript>
55
+
56
+ #### Busting the Cache
57
+
58
+ Each time CSS is compile, it is cached using the cache key: `[controller, action, version]`.
59
+
60
+ By default, we used Heroku's environment variable `HEROKU_RELEASE_VERSION` to bust the version cache. This is available
61
+ through the [Heroku Labs: Dyno Metadata](https://devcenter.heroku.com/articles/dyno-metadata).
62
+
63
+ If this doesn't work for you, set the `version` flag in config to some other deploy-unique id, so that new CSS can be
64
+ generated for you each time you change your pages.
65
+
66
+ ## Configuration Options
67
+
68
+ In `config/initializers/critical_css_server.rb`:
69
+
70
+ RailsCriticalCssServer.config do |c|
71
+ c.host = ENV['CRITICAL_CSS_SERVER_URL'] # URL of Critical CSS Server
72
+ c.auth_token = ENV['CRITICAL_CSS_SERVER_AUTH_TOKEN'] # Credentials for Critical CSS Server
73
+ c.timeout = 0.05 # Timeout when requested critical CSS in layout.
74
+ c.version = ENV['HEROKU_RELEASE_VERSION'] # Unique id for the current deploy. Used to bust the cache after changes are made
75
+ c.width = 900 # width of viewport to optimize CSS for
76
+ c.height = 1200 # height of viewport to optimize CSS for
77
+ c.force_selectors = [] # force individual selectors to be included, even if they are not rendered on the first pass. Useful for JavaScript-enabled styles.
78
+ end
79
+
80
+ ## Under the hood:
81
+
82
+ * [CriticalCSS](https://github.com/filamentgroup/criticalCSS) - used to generate CSS rules
83
+ * [loadCSS](https://github.com/filamentgroup/loadCSS) - defer loading of remainder of CSS
84
+
85
+ ## License
86
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,36 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+
9
+ RDoc::Task.new(:rdoc) do |rdoc|
10
+ rdoc.rdoc_dir = 'rdoc'
11
+ rdoc.title = 'RailsCriticalCssServer'
12
+ rdoc.options << '--line-numbers'
13
+ rdoc.rdoc_files.include('README.md')
14
+ rdoc.rdoc_files.include('lib/**/*.rb')
15
+ end
16
+
17
+ APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__)
18
+ load 'rails/tasks/engine.rake'
19
+
20
+
21
+ load 'rails/tasks/statistics.rake'
22
+
23
+
24
+
25
+ require 'bundler/gem_tasks'
26
+
27
+ require 'rake/testtask'
28
+
29
+ Rake::TestTask.new(:test) do |t|
30
+ t.libs << 'lib'
31
+ t.libs << 'test'
32
+ t.pattern = 'test/**/*_test.rb'
33
+ t.verbose = false
34
+ end
35
+
36
+ task default: :test
@@ -0,0 +1,14 @@
1
+ <style type='text/css' id='critical-css-server-inlined'>
2
+ <%= critical_css.html_safe %>
3
+ </style>
4
+
5
+ <%= render 'rails_critical_css_server/inline_load_css_script' %>
6
+ <script id='critical-css-server-deferred'>
7
+ <% css_files.each do |href| %>
8
+ loadCSS("<%= href %>");
9
+ <% end %>
10
+ </script>
11
+
12
+ <noscript>
13
+ <%= original_html.html_safe %>
14
+ </noscript>
@@ -0,0 +1,4 @@
1
+ <script type='application/javascript'>
2
+ /*! loadCSS: load a CSS file asynchronously. [c]2016 @scottjehl, Filament Group, Inc. Licensed MIT */
3
+ !function(e){"use strict";var n=function(n,t,o){function i(e){return a.body?e():void setTimeout(function(){i(e)})}function r(){l.addEventListener&&l.removeEventListener("load",r),l.media=o||"all"}var d,a=e.document,l=a.createElement("link");if(t)d=t;else{var s=(a.body||a.getElementsByTagName("head")[0]).childNodes;d=s[s.length-1]}var f=a.styleSheets;l.rel="stylesheet",l.href=n,l.media="only x",i(function(){d.parentNode.insertBefore(l,t?d:d.nextSibling)});var u=function(e){for(var n=l.href,t=f.length;t--;)if(f[t].href===n)return e();setTimeout(function(){u(e)})};return l.addEventListener&&l.addEventListener("load",r),l.onloadcssdefined=u,u(r),l};"undefined"!=typeof exports?exports.loadCSS=n:e.loadCSS=n}("undefined"!=typeof global?global:this);
4
+ </script>
@@ -0,0 +1,12 @@
1
+ require 'rails_critical_css_server/engine'
2
+ require 'rails_critical_css_server/callable'
3
+ require 'rails_critical_css_server/config'
4
+ require 'rails_critical_css_server/client'
5
+ require 'rails_critical_css_server/extract_css_from_html'
6
+ require 'rails_critical_css_server/rewrite'
7
+
8
+ module RailsCriticalCssServer
9
+ def self.config
10
+ yield RailsCriticalCssServer::Config
11
+ end
12
+ end
@@ -0,0 +1,7 @@
1
+ module RailsCriticalCssServer
2
+ module Callable
3
+ def call(*args, &block)
4
+ new(*args, &block).call
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,52 @@
1
+ require 'httparty'
2
+
3
+ module RailsCriticalCssServer
4
+ class Client
5
+ include HTTParty
6
+ attr_reader :manifest, :key, :url, :token
7
+
8
+ NAMESPACE = 'critical-css:'
9
+
10
+ def initialize(key, url, manifest, base_uri: Config.host, timeout: Config.timeout, token: Config.auth_token)
11
+ @key = key
12
+ @manifest = manifest
13
+ @url = url
14
+ @token = token
15
+ self.class.base_uri base_uri
16
+ self.class.default_timeout timeout
17
+ end
18
+
19
+ def read!
20
+ self.class.post('/api/v1/css',
21
+ headers: auth.merge(json_headers),
22
+ body: { page: page_data, config: Config.read_options }.to_json)
23
+ rescue => e
24
+ log_error e
25
+ nil
26
+ end
27
+
28
+ def page_data
29
+ { key: full_key, css: manifest, url: url }
30
+ end
31
+
32
+ def log_error(error)
33
+ Rails.logger.error error
34
+ end
35
+
36
+ private
37
+
38
+ def full_key
39
+ "#{NAMESPACE}:#{key}"
40
+ end
41
+
42
+ def auth
43
+ {
44
+ 'x-access-token' => token
45
+ }
46
+ end
47
+
48
+ def json_headers
49
+ { 'Content-Type' => 'application/json' }
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,43 @@
1
+ module RailsCriticalCssServer
2
+ class Config
3
+ class << self
4
+ attr_writer :host, :version, :timeout, :force_selectors, :auth_token, :width, :height
5
+
6
+ def timeout
7
+ @timeout ||= 0.05
8
+ end
9
+
10
+ def host
11
+ @host ||= ENV['CRITICAL_CSS_SERVER_URL']
12
+ end
13
+
14
+ def version
15
+ @version ||= ENV['HEROKU_RELEASE_VERSION']
16
+ end
17
+
18
+ def auth_token
19
+ @auth_token ||= ENV['CRITICAL_CSS_SERVER_AUTH_TOKEN']
20
+ end
21
+
22
+ def force_selectors
23
+ @force_selectors ||= []
24
+ end
25
+
26
+ def width
27
+ @width ||= 1200
28
+ end
29
+
30
+ def height
31
+ @height ||= 900
32
+ end
33
+
34
+ def read_options
35
+ {
36
+ 'forceInclude' => force_selectors,
37
+ 'width' => width,
38
+ 'height' => height
39
+ }
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,4 @@
1
+ module RailsCriticalCssServer
2
+ class Engine < ::Rails::Engine
3
+ end
4
+ end
@@ -0,0 +1,16 @@
1
+ module RailsCriticalCssServer
2
+ class ExtractCssFromHtml
3
+ extend Callable
4
+ attr_reader :html
5
+
6
+ def initialize(html)
7
+ @html = html
8
+ end
9
+
10
+ def call
11
+ regex = /<link.+href=\"([^"]+\.css[^"]*)\"/
12
+
13
+ html.gsub(/<link/, "\n<link").scan(regex).flatten
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,83 @@
1
+ module RailsCriticalCssServer
2
+ class Rewrite
3
+ extend Callable
4
+
5
+ attr_reader :template, :manifest, :version, :block, :skip, :cache
6
+
7
+ delegate :request, :params, to: :template
8
+
9
+ def initialize(template, manifest: template.asset_url('application.css'), version: Config.version, skip: false, cache: true, &block)
10
+ @template = template
11
+ @manifest = manifest
12
+ @version = version
13
+ @skip = skip
14
+ @block = block
15
+ @cache = cache
16
+ end
17
+
18
+ def call
19
+ return original_html unless should_run?
20
+ return cached_value if cache && cached_value.present?
21
+ return original_html unless content_ready?
22
+
23
+ Rails.cache.write(self, rewritten_html) if cache
24
+ rewritten_html
25
+ end
26
+
27
+ def cache_key
28
+ [version, manifest, key].join(':')
29
+ end
30
+
31
+ private
32
+
33
+ def cached_value
34
+ return @cached_value if defined? @cached_value
35
+ @cached_value = Rails.cache.read(self)
36
+ end
37
+
38
+ def content
39
+ @content ||= client.read!
40
+ end
41
+
42
+ def content_ready?
43
+ content.present? && content.ok?
44
+ end
45
+
46
+ def original_html
47
+ return @original_html if defined? @original_html
48
+ @original_html = template.capture { block.call }
49
+ end
50
+
51
+ def rewritten_html
52
+ return @rewritten_html if defined? @rewritten_html
53
+ css_files = ExtractCssFromHtml.call(original_html)
54
+
55
+ @rewritten_html = template.capture do
56
+ template.render 'rails_critical_css_server/css_load',
57
+ css_files: css_files,
58
+ critical_css: content,
59
+ original_html: original_html
60
+ end
61
+ end
62
+
63
+ def should_run?
64
+ !skip && !phantomjs_useragent? && Config.host.present?
65
+ end
66
+
67
+ def phantomjs_useragent?
68
+ request.user_agent.match(/PhantomJS/)
69
+ end
70
+
71
+ def client
72
+ @client ||= Client.new(key, request.original_url, manifest)
73
+ end
74
+
75
+ def key
76
+ "#{params[:controller]}##{params[:action]}:#{version}"
77
+ end
78
+
79
+ def to_s
80
+ self.class.to_s
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,3 @@
1
+ module RailsCriticalCssServer
2
+ VERSION = '0.1.0'
3
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :rails_critical_css_server do
3
+ # # Task goes here
4
+ # end
metadata ADDED
@@ -0,0 +1,102 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rails_critical_css_server
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Michael Wheeler
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2017-02-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '3.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '3.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: httparty
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.13.3
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.13.3
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Client for critical_css_server. This server generates the critical path
56
+ CSS for you. It is designed to sit alongside your production app, and prepare the
57
+ critical CSS asynchronously.
58
+ email:
59
+ - mwheeler@g2crowd.com
60
+ executables: []
61
+ extensions: []
62
+ extra_rdoc_files: []
63
+ files:
64
+ - MIT-LICENSE
65
+ - README.md
66
+ - Rakefile
67
+ - app/views/rails_critical_css_server/_css_load.html.erb
68
+ - app/views/rails_critical_css_server/_inline_load_css_script.html
69
+ - lib/rails_critical_css_server.rb
70
+ - lib/rails_critical_css_server/callable.rb
71
+ - lib/rails_critical_css_server/client.rb
72
+ - lib/rails_critical_css_server/config.rb
73
+ - lib/rails_critical_css_server/engine.rb
74
+ - lib/rails_critical_css_server/extract_css_from_html.rb
75
+ - lib/rails_critical_css_server/rewrite.rb
76
+ - lib/rails_critical_css_server/version.rb
77
+ - lib/tasks/rails_critical_css_server_tasks.rake
78
+ homepage: https://github.com/wheeyls/rails_critical_css_server
79
+ licenses:
80
+ - MIT
81
+ metadata: {}
82
+ post_install_message:
83
+ rdoc_options: []
84
+ require_paths:
85
+ - lib
86
+ required_ruby_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ required_rubygems_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ requirements: []
97
+ rubyforge_project:
98
+ rubygems_version: 2.4.8
99
+ signing_key:
100
+ specification_version: 4
101
+ summary: Prioritize above-the-fold CSS in a Rails application
102
+ test_files: []