Loading Google Analytics using Polymer

Polymer and web components are great and they help us develop our apps faster. One component that I’d expect to see is <google-analyitics>. I want to be able to plug in Google Analytics (GA) quickly and easy. I want the component to “feel” and behave in “polymer-y” way. I don’t want to worry if I load it eagerly or lazily, whether I provide key at page load or I get it later.

We’ll make our own my-ga (short for “my-google-analytics”) component. It will allow you to do embed it like any other component (<my-ga key$="[[config.gaKey]]"). It will also behave “as expected” when used within single page app (SPA). This means that URL changes will be sent as page views (which is what most people expect). There is one assumptions though. We assume that you will use this component with Polymer framework.

Making my-ga

Let’s start of by registering our component in my-ga.html.

document.registerElement('my-ga', {
prototype: {
__proto__: HTMLElement.prototype,
attributeChangedCallback: () => {

There are multiple lifecycle methods that we could hook into when using custom elements. In our case attributeChangedCallback is the most appropriate one. It will be called when we set key attribute. The implementation will be quite simple as we can assume that the only attribute set on this element is key one.

It’s time to insert our GA code:

This will load GA only once key is set. This is good as it allows us to have a component included but “not do anything” until we set the key. If we know they key we want to use, we can set it immediately and GA will be loaded as soon as possible.

Tweaking for single-page apps

There is one issue here. This will fire pageview event only on initial load, when GA is loaded.. Assuming you’re working on a web application, your URL (in the address bar) will change as the application state changes. My assumption is that most people will expect to see that change in form of pageview event in their GA dashboard. Polymer provides component called app-location which gives your application access to location. It also fires location-changed event whenever the address changes. Whenever this event is fired we should send a pageview event with correct information (path). To do that, we can attach an event listener to our window object:

window.addEventListener('location-changed', function() {
ga('set', 'page', window.location.pathname);
ga('send', 'pageview');

In the end, this is what your my-ga component should look like:

You can now import it in order to hook your SPA with Google Analytics. Don’t forget to also include app-location in case you want to see address changes as pageviews in GA.