diff --git a/app/helpers/script_helper.rb b/app/helpers/script_helper.rb index c6c0e49e053..73c2786ced3 100644 --- a/app/helpers/script_helper.rb +++ b/app/helpers/script_helper.rb @@ -19,14 +19,27 @@ def javascript_packs_tag_once(*names, prepend: false) def render_javascript_pack_once_tags(*names) javascript_packs_tag_once(*names) if names.present? if @scripts && (sources = AssetSources.get_sources(*@scripts)).present? - safe_join([javascript_polyfill_pack_tag, javascript_include_tag(*sources)]) + safe_join( + [ + javascript_polyfill_pack_tag, + javascript_include_tag(*sources, crossorigin: local_crossorigin_sources? ? true : nil), + ], + ) end end private + def local_crossorigin_sources? + Rails.env.development? && ENV['WEBPACK_PORT'].present? + end + def javascript_polyfill_pack_tag - javascript_include_tag_without_preload(*AssetSources.get_sources('polyfill'), nomodule: '') + javascript_include_tag_without_preload( + *AssetSources.get_sources('polyfill'), + nomodule: '', + crossorigin: local_crossorigin_sources? ? true : nil, + ) end def without_preload_links_header diff --git a/spec/helpers/script_helper_spec.rb b/spec/helpers/script_helper_spec.rb index f8cee5fcce4..96b08089144 100644 --- a/spec/helpers/script_helper_spec.rb +++ b/spec/helpers/script_helper_spec.rb @@ -40,13 +40,44 @@ output = render_javascript_pack_once_tags expect(output).to have_css( - "script[src^='/polyfill.js'][nomodule] ~ \ - script[src^='/application.js'] ~ \ - script[src^='/document-capture.js']", + "script:not([crossorigin])[src^='/polyfill.js'][nomodule] ~ \ + script:not([crossorigin])[src^='/application.js'] ~ \ + script:not([crossorigin])[src^='/document-capture.js']", count: 1, visible: :all, ) end + + context 'local development crossorigin sources' do + let(:webpack_port) { '3035' } + + before do + allow(Rails.env).to receive(:development?).and_return(true) + stub_const('ENV', 'WEBPACK_PORT' => webpack_port) + end + + it 'prints script sources with crossorigin attribute' do + output = render_javascript_pack_once_tags + + expect(output).to have_css( + "script[crossorigin][src^='/polyfill.js'][nomodule] ~ \ + script[crossorigin][src^='/application.js'] ~ \ + script[crossorigin][src^='/document-capture.js']", + count: 1, + visible: :all, + ) + end + + context 'empty webpack port' do + let(:webpack_port) { '' } + + it 'renders as if webpack port was unassigned' do + output = render_javascript_pack_once_tags + + expect(output).to_not have_css('[crossorigin]', visible: :all) + end + end + end end context 'with named scripts argument' do