This lets you set the preload headers for your assets, so that the browser can start fetching them before it begins parsing HTML.
Rails Link Preload Headers
class ApplicationController < ActionController::Base | |
include ::PreloadHeaders | |
protected | |
def preload_header_assets | |
[ | |
{path: 'application.css', as: 'style'}, | |
({path: 'application.js', as: 'script'} unless Rails.application.config.assets.debug), | |
{path: 'logo.png', as: 'image'}, | |
].compact | |
end | |
end |
# app/controllers/concerns/preload_headers.rb | |
module PreloadHeaders | |
extend ActiveSupport::Concern | |
included do | |
after_action :set_preload_headers | |
end | |
protected | |
def set_preload_headers | |
return if !request.format.html? || request.xhr? || | |
# Turbolinks 2 | |
request.headers['X-XHR-Referer'].present? || | |
# Turbolinks 5 | |
request.env['HTTP_TURBOLINKS_REFERRER'] | |
response.headers['Link'] = preload_header_assets.map do |asset| | |
"<#{view_context.asset_path(asset[:path])}>; rel=preload; as=#{asset[:as]}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment