Skip to content

Instantly share code, notes, and snippets.

@glebm

glebm/README.md

Last active Dec 29, 2019
Embed
What would you like to do?
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