Ensure modules are preloaded correctly using rel=modulepreload.

Prior to this change, javascript_include_tag was sending a hint using
rel="preload" for all scripts, including those of type="module".

This causes the browser to make a request to preload the script, but
because the rel is incorrect, it won't be able to reuse it.

When passing type="module", it should use rel=modulepreload instead.

[0] developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
[1] developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
[2] developer.mozilla.org/en-US/docs/Web/HTML/Link_types/modulepreload
This commit is contained in:
Máximo Mussini 2021-03-19 14:22:22 -03:00 committed by GitHub
parent b5c4af7d52
commit 1598ad5c4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 1 deletions

@ -94,11 +94,12 @@ def javascript_include_tag(*sources)
crossorigin = options.delete("crossorigin")
crossorigin = "anonymous" if crossorigin == true
integrity = options["integrity"]
rel = options["type"] == "module" ? "modulepreload" : "preload"
sources_tags = sources.uniq.map { |source|
href = path_to_javascript(source, path_options)
if preload_links_header && !options["defer"]
preload_link = "<#{href}>; rel=preload; as=script"
preload_link = "<#{href}>; rel=#{rel}; as=script"
preload_link += "; crossorigin=#{crossorigin}" unless crossorigin.nil?
preload_link += "; integrity=#{integrity}" unless integrity.nil?
preload_link += "; nopush" if nopush

@ -554,6 +554,14 @@ def test_should_set_preload_links_with_cross_origin
end
end
def test_should_set_preload_links_with_rel_modulepreload
with_preload_links_header do
javascript_include_tag("http://example.com/all.js", type: "module")
expected = "<http://example.com/all.js>; rel=modulepreload; as=script; nopush"
assert_equal expected, @response.headers["Link"]
end
end
def test_should_set_preload_links_with_integrity_hashes
with_preload_links_header do
stylesheet_link_tag("http://example.com/style.css", integrity: "sha256-AbpHGcgLb+kRsJGnwFEktk7uzpZOCcBY74+YBdrKVGs")