Making Google Analytics and Partytown work: lazy-load thrid party libraries
Table of Contents
Partytown is a library dedicated to offloading third-party libraries such as tracking scripts to a web worker, i.e. downloading and executing them in the background. Partytown is easy to install but is still in beta and the documentation is a little lacking. To make Partytown and Google Analytics work as expected in relation to Google Analytics’ official documentation, two changes are necessary. Here’s how to install Partytown and Google Analytics in an Astro web app:
#
1. Install the Partytown library:
yarn add @qwik.dev/partytown
#
2. Add Partytown to the build script in package.json
package.json
This copies the Partytown script to Astro’s static directory ./public/~partytown.
// ...
"scripts": {
"build": "yarn partytown && astro astro-check && astro build",
"partytown": "partytown copylib 'public/~partytown'"
}
// ...
#
3. Add Google Analytics to the main layout file e.g. ./src/layouts/Layout.astro:
./src/layouts/Layout.astro:
The two changes neccessary to make Google Analytics and Partytown work is to: forward gtag to Partytown and manually fire the standard page_view event.
<!-- Forward "gtag" as well as "dataLayer.push" and only load it in production -->
{import.meta.env.PROD ? <Partytown forward={['dataLayer.push', 'gtag']} /> : ''}
<script is:inline type="text/partytown" src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_CODE" async></script>
<script is:inline type="text/partytown">
window.dataLayer = window.dataLayer || [];
window.gtag = function gtag() {
dataLayer.push(arguments);
};
window.gtag('js', new Date());
// First change: Normally this fires page_view but it doesn't when using Astro
window.gtag('config', 'GA_TRACKING_CODE', { send_page_view: false });
// Second change: Manually fire page_view event
window.gtag('event', 'page_view', { page_title: document.title, page_location: location.href });
</script>
Now, the heavy Google Analytics library is lazy-loaded and sends a “page_view” event. You can see it in action on app.sqlai.ai and see that a “page_view” event is sent. The web app has a 100% score on Page Speed.
#
4. Track events throughout the Astro web app:
Add a file in ./src/lib/google-analytics.ts (or wherever you desire) with the following content:
export const ga = (action: string, options?: Record<string, any> & { label?: string; value?: number }) => {
if (typeof window !== 'undefined' && 'gtag' in window && typeof window.gtag === 'function') {
window.gtag('event', action, { ...options, category: 'Web' });
}
};
Use the tracking helper function like this:
ga('database_engine_changed', { label: databaseEngine }); // label works as custom variable related to the tracking, e.g. selected database engine