govuk_publishing_components
govuk_publishing_components copied to clipboard
Use Google snippet for GTM in analytics JavaScript
What
- include the code snippet from Google in our code for running GTM as part of our new analytics code
- note that this will not work without the id, auth and preview values, which have to be created separately before the analytics code is called in
static
Note that none of this code will be executed in production yet. This also depends upon the correct environment variables being set for the GTM code variables (see related PR, not ready yet).
How this works:
-
static
includesanalytics-ga4.js
(only on integration) -
static
gets the GTM variables forid
,auth
andpreview
from environment variables using the functionality available throughjs.erb
and sets them as JS variables inside thewindow.analyticsGA4.vars
object -
static
then callswindow.GOVUK.analyticsGA4.init()
(init-ga4.js
in the gem) - the analytics code is set up and configured, beginning first with the
core.load
function inga4-core.js
, which runs the Google code snippet, inserting the variables forid
,auth
andpreview
from thewindow.analyticsGA4.vars
object
A few thoughts on this:
- I'm not sure what tests can be written for
ga4-core.js
as all it currently does is run the code snippet from Google, but I'm open to suggestions - 'core' was the best name I could think of for this code, but I'm not sure I like it, so again any suggestions welcome
- core seems a bit empty at the moment, but I'm planning for it to be the home for more code, specifically the generic 'push things to the dataLayer' function
Why
We're moving to integrate this analytics code fully with the cookie consent mechanism, which means no code from Google will be called unless users consent to cookies.
Visual Changes
None.
Trello card: https://trello.com/c/vrMj18et/353-integrate-gtm-with-cookie-consent-mechanism