Skip to content

Commit

Permalink
Make Google charts script load only once
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
andysellick committed Oct 22, 2024
1 parent 8e55e2e commit 03f2ac9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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", {
Expand Down
8 changes: 8 additions & 0 deletions spec/components/chart_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 03f2ac9

Please sign in to comment.