Created
October 27, 2018 20:35
-
-
Save ndbroadbent/d9818b2ca341207036eaa87e6ff93335 to your computer and use it in GitHub Desktop.
HTTP/2 Server Push for Rails - Add Link preload headers for all CSS and image assets on your home page
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
module PreloadHelper | |
def compute_asset_path(*args) | |
computed_path = super | |
add_link_header_for_computed_asset_path(computed_path) | |
computed_path | |
end | |
protected | |
# Preload all CSS and images on the home index page. | |
def add_link_header_for_computed_asset_path(path) | |
return unless Rails.env.production? && | |
current_page?(controller: 'home', action: 'index') | |
asset_type = case path | |
when /\/home\/ie(8|9)/ then return # Skip IE CSS | |
when /\.css(\?|$)/ then 'style' | |
when /\.(svg|png|jpg)(\?|$)/ then 'img' | |
else return | |
end | |
response.headers['Link'] ||= [] | |
response.headers['Link'] << "<#{path}>; rel=preload; as=#{asset_type}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment