Friday, September 11, 2015

How Do I Make Google Analytics Working With Turbolinks 3

One of websites uses full page caching and it has very good performance. But I want to make it faster by putting Turbolinks to my website. With Turbolinks, the browser will not recompile my Javascript and CSS each page change and speed up my website.

But the other problem occur. The problem is Google Analytics always send pageview for same URL because of Turbolinks does not recompile javascript from Google Analytics

Turbolinks basically uses XHR request each page change and always evaluate script tag inside inside HTML body. Google Analytics need to send pageview on every page change.

So to make Google Analytics with Turbolinks, I should make Turbolinks evaluates send pageview function from Google Analitycs every page change.

    <% if Rails.env.production? %>
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

        ga('create', 'YOUR_GOOGLE_ANALYTICS_ID', 'auto');
    <% end %>
    <% if Rails.env.production? %>
        ga('send', 'pageview', '<%= request.fullpath %>');
    <% end %>

No comments:

Post a Comment

© Railsmine