digital-analytics-program / gov-wide-code

Provides a set of javascript files and documentation to implement web analytics on US federal websites
http://www.digital.gov/dap
104 stars 55 forks source link

Load Google Tag Manager script as asynchronous #121

Open aduth opened 3 months ago

aduth commented 3 months ago

This pull request proposes to create the Google Tag Manager script using the async attribute on the script element` (see MDN reference).

The DAP script appends a Google Tag Manager script to the page, but it does so without marking the script as asynchronous. This causes the script to block the main thread, impacting user-facing performance.

This reflects in performance audits of our site, which flag Google Tag Manager as blocking main thread for upward of 300ms.

Related resource: https://web.dev/articles/optimizing-content-efficiency-loading-third-party-javascript#async-defer

Google's documentation for Google Tag Manager also uses async in its own default script snippet examples:

Screenshot 2024-08-16 at 9 31 58 AM