diff --git a/app/views/govuk_publishing_components/components/_chart.html.erb b/app/views/govuk_publishing_components/components/_chart.html.erb index 09101aa3d4..81112c6e28 100644 --- a/app/views/govuk_publishing_components/components/_chart.html.erb +++ b/app/views/govuk_publishing_components/components/_chart.html.erb @@ -20,6 +20,8 @@ chart_id = "chart-id-#{SecureRandom.hex(4)}" table_id = "table-id-#{SecureRandom.hex(4)}" + @external_script ||= OpenStruct.new(loaded: 0) + @external_script[:loaded] += 1 shared_helper = GovukPublishingComponents::Presenters::SharedHelper.new(local_assigns) component_helper = GovukPublishingComponents::Presenters::ComponentWrapperHelper.new(local_assigns) @@ -79,7 +81,7 @@ end %> <% if rows.length > 0 && keys.length > 0 && valid_minimal %> - <%= javascript_include_tag "https://www.gstatic.com/charts/loader.js" %> + <%= javascript_include_tag "https://www.gstatic.com/charts/loader.js" if @external_script[:loaded] == 1 %> <%= tag.div(**component_helper.all_attributes) do %> <% if chart_heading && !minimal %> <%= render "govuk_publishing_components/components/heading", { diff --git a/spec/components/chart_spec.rb b/spec/components/chart_spec.rb index 03ba7bfd13..34d14937c8 100644 --- a/spec/components/chart_spec.rb +++ b/spec/components/chart_spec.rb @@ -124,4 +124,12 @@ def component_name data[:minimal] = true assert_empty render_component(data) end + + it "only calls an external script once" do + render_component(data) + data[:classes] = "" # need to 'reset' this otherwise it carries from the first component and breaks shared_helper + render_component(data) + + assert_select 'script[src="https://www.gstatic.com/charts/loader.js"]', count: 1 + end end