Fork me on GitHub

Tracking

It's a good practice to track websites traffic and other datas using tools like Google Analytics or Google Tag Manager. Tracking datas help developers understand how users are using their website and learn where there might be some improvements to do to the user-experience.

Google Analytics

Google Analytics is a tool among many others to track datas on websites. One of the most tracked and useful data is the page views on websites to learn where users are going and how many users visited the pages of websites. Unfortunately with Highway and more globally AJAX navigation the page views sent to Google Analytics will always be the same for all pages users will visit because the script in the head tag isn't reloaded on navigation.

The script being outside of the data-router-wrapper as it should, it isn't updated on navigation and developers need to programmatically send those page views to Google Analytics with Highway events. The NAVIGATE_END event fits perfectly for this kind of behavior.

<!-- File: index.html -->
<!-- [...] -->
<head>
  <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }
  </script>
</head>
<!-- [...] -->

// File: main.js
const H = new Highway.Core();

// Listen the `NAVIGATE_END` event
H.on('NAVIGATE_END', ({ from, to, location }) => {
  // Analytics
  if (typeof gtag !== 'undefined') {
    // eslint-disable-next-line
    gtag('config', 'UA-XXXXXXXXX-X', {
      'page_path': location.pathname,
      'page_title': to.page.title,
      'page_location': location.href
    });
  }
});

Google Tag Manager

Another tool to track datas on websites is Google Tag Manager. The difference with Google Analytics is that page views don't really need to be sent programmatically since the Google Tag Manager configuration provide the History Change Trigger which can be used to watch all history changes and automatically track new page views.

Other Tools

Developers are free to use any tools needed to track datas from websites. Since those tools might need scripts in the head tag or before the closing body tag those will be outside of the data-router-wrapper of the pages and they won't be updated on navigation.

The solution with Highway as showcased with Google Analytics is to use events so developers will be able to send datas to track with Javascript. Refer to the documentation of those tools to send datas programmatically.