Skip to content

Instantly share code, notes, and snippets.

@glebm
Last active March 29, 2023 19:56
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glebm/99ac846ece802fa1f686d5e75ae7bfef to your computer and use it in GitHub Desktop.
Save glebm/99ac846ece802fa1f686d5e75ae7bfef to your computer and use it in GitHub Desktop.
Rails Link Preload Headers

This lets you set the preload headers for your assets, so that the browser can start fetching them before it begins parsing HTML.

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