From 62d6e712729ea7f2c6e273638976963829e289a7 Mon Sep 17 00:00:00 2001 From: Andy Sellick Date: Mon, 21 Oct 2024 11:56:16 +0100 Subject: [PATCH] Make Google charts script load only once - use an Openstruct to persist a value between multiple instances of the component to make the external script for Google charts only be called once - perhaps unsurprisingly this doesn't make any difference to the page weight in Chrome, presumably because Chrome is smart enough to realise it's already loaded that script if there's more than one chart - however it feels tidier to limit it this way, particularly for browsers that may not be so clever --- .../components/_chart.html.erb | 4 +++- spec/components/chart_spec.rb | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/app/views/govuk_publishing_components/components/_chart.html.erb b/app/views/govuk_publishing_components/components/_chart.html.erb index 22b64e1c8e..2691e64e11 100644 --- a/app/views/govuk_publishing_components/components/_chart.html.erb +++ b/app/views/govuk_publishing_components/components/_chart.html.erb @@ -23,6 +23,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) @@ -82,7 +84,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