falsandtru / pjax-api

The advanced PJAX superior to SPA.
https://falsandtru.github.io/pjax-api/
Apache License 2.0
318 stars 28 forks source link

Google Analytics #20

Closed hugofabricio closed 8 years ago

hugofabricio commented 8 years ago

What would be the best way to insert google analytics?

I tried in

$ (document) .on ('pjax: ready', function () {
window.ga ( 'send', 'pageview', {page: document.location.pathname, title: document.title});
}

But by analyzing the google analytics sometimes even the pathname are correct and sent the root '/', there is a more appropriate way?

falsandtru commented 8 years ago

See my implementation.

  <script>
    if (!window.ga) {
      (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
          (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
      })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
      ga('create', 'UA-43533651-1', 'auto');
      ga('require', 'linkid', 'linkid.js');
      ga('require', 'displayfeatures');
    }
    ga('send', 'pageview', window.location.pathname.replace(/^\/?/, '/') + window.location.search);
  </script>

https://github.com/falsandtru/pjax-api/blob/gh-pages/_layouts/layout.html

External scripts will be run once per url. Inline scripts will be run everytime.

hugofabricio commented 8 years ago

Solved.