Ruby & Rails
W1siziisijiwmtmvmdqvmjuvmtuvndqvmzavntcxl1cxc2laaulzsw5cewiyujfzm1jwyji0dk1qqxhneth3tkm4d015ohhoetgxtvm4mu1dohhoall2wm1sc1ptsmryuv9lzjzhotlinc5qcgvnil1d-53364eba

Hendrik Mans - March 18, 2013

Make GoSquared work with Rails Turbolinks

Turbolinks is a new official Rails gem that automagically ‘pjaxes’ your site, making all links (to GET resources) load through AJAX instead of triggering a full new browser request cycle. Since your browser doesn’t need to deal with processing assets (stylesheets, JavaScript etc.) on each request, this will significantly increase page load performance. The big drawback is that this will have a noticeable impact on how you work with JavaScript, since you can’t just tie stuff to the document.onload event and expect it to work (since this event will simply not be triggered more than once).

Luckily, there’s a bunch of (mostly easy to apply) workarounds available. However, I wasn’t able to find a documented fix for making the GoSquared tracking code work with Turbolinks, so with a bit of help from my favorite JavaScript (and love) guru @carlo, I came up with the following solution.

Instructions

  1. Move the GoSquared tracker code into your site’s <head>.
  2. Add the following piece of CoffeeScript code:
1$(document).on 'page:change', ->
2  GoSquared.DefaultTracker.TrackView()

Explanation

The official GoSquared instructions will ask you to embed the tracker code at the very end of your <body>. By moving it into the <head> section of your site, we’re making sure it’ll only be loaded and initialized once within a Turbolinks session.

Turbolinks conveniently triggers a page:change event every time a new page is loaded through it, which we’ll use to invoke the GoSquared.DefaultTracker.TrackView function (which, as its name implies, will track the view with GoSquared, which is exactly what we want.)

Take a look at this page for some additional information. Big thanks to @carlo for helping me figure this out. \o/

W1siziisijiwmtmvmdkvmjuvmtuvmzgvntevmte2l2htyw5zx2j1zxjzdguyx3nxdwfyzs5qcgcixsxbinailcj0ahvtyiisijeymhgxmjajil1d-145faed7

Developer dude from Hamburg, Germany. Among other things, runs sloblog.io. Not good with descriptions. Don’t follow me on Twitter. ★

Loading comments...

Please sign in to post a comment.