Skip to content

Instantly share code, notes, and snippets.

@ndbroadbent
Created October 27, 2018 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndbroadbent/d9818b2ca341207036eaa87e6ff93335 to your computer and use it in GitHub Desktop.
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
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