FEATURE: Preload resources via link header (#18475)

Experiment moving from preload tags in the document head to preload information the the response headers.

While this is a minor improvement in most browsers (headers are parsed before the response body), this allows smart proxies like Cloudflare to "learn" from those headers and build HTTP 103 Early Hints for subsequent requests to the same URI, which will allow the user agent to download and parse our JS/CSS while we are waiting for the server to generate and stream the HTML response.

Co-authored-by: Penar Musaraj <pmusaraj@gmail.com>
This commit is contained in:
Rafael dos Santos Silva
2022-10-07 13:19:50 -03:00
committed by GitHub
parent a1d67122b1
commit 2d1dbc6f96
7 changed files with 107 additions and 17 deletions

View File

@@ -142,12 +142,16 @@ module ApplicationHelper
end
def preload_script_url(url)
add_resource_preload_list(url, 'script')
<<~HTML.html_safe
<link rel="preload" href="#{url}" as="script">
<script defer src="#{url}"></script>
HTML
end
def add_resource_preload_list(resource_url, type)
@links_to_preload << %Q(<#{resource_url}>; rel="preload"; as="#{type}") if !@links_to_preload.nil?
end
def discourse_csrf_tags
# anon can not have a CSRF token cause these are all pages
# that may be cached, causing a mismatch between session CSRF
@@ -589,7 +593,7 @@ module ApplicationHelper
stylesheet_manager
end
manager.stylesheet_link_tag(name, 'all')
manager.stylesheet_link_tag(name, 'all', self.method(:add_resource_preload_list))
end
def discourse_preload_color_scheme_stylesheets
@@ -605,10 +609,10 @@ module ApplicationHelper
def discourse_color_scheme_stylesheets
result = +""
result << stylesheet_manager.color_scheme_stylesheet_link_tag(scheme_id, 'all')
result << stylesheet_manager.color_scheme_stylesheet_link_tag(scheme_id, 'all', self.method(:add_resource_preload_list))
if dark_scheme_id != -1
result << stylesheet_manager.color_scheme_stylesheet_link_tag(dark_scheme_id, '(prefers-color-scheme: dark)')
result << stylesheet_manager.color_scheme_stylesheet_link_tag(dark_scheme_id, '(prefers-color-scheme: dark)', self.method(:add_resource_preload_list))
end
result.html_safe