Where developers come to connect, share, build and be inspired.


Faster page loads with Turbolinks


Rails released their Turbolinks gem, which is a small JavaScript snippet that loads your pages via AJAX. The net result is an app that feels more responsive.

Here's a guide to Turbolinks's caveats that I gathered from experience.

Load order

You need to have this load order below:

The reason for jQuery.turbolinks being before all scripts is so to let it hijack the $(function() { ... }) call that your other scripts will use.

Turbolinks then needs to be at the end because it has to be the last to install the click handler, so not to interfere with other scripts.

Scripts in head

You may be putting your scripts at the end of the <body> tag. If you're using Turbolinks, move them back to <head>. The reason for this is that Turbolinks works by swapping out the <body> when changing pages, and doing so will re-execute all your third-party scripts (imagine jQuery being re-evaluated), which may not be what you want.

head scripts must NOT change

Always go by the assumption that all Turbolinks-enabled pages should have the <head> contents. If any page doesn't fit this standard, either refactor it or opt it out of turbolinks (<a href='...' data-no-turbolink>).

Loading spinner

You WILL need a loading indicator! This should be pretty easy to do:

$(document).on('page:fetch', function() {
$(document).on('page:change', function() {

Every Turbolinks site will need this, otherwise it will feel very weird that clicking a link will seem to do nothing.

Google analytics integration

If you put your Google analytics script in your <head> (like Google recommends), it will only fire once and not fire again when changing pages via Turbolinks.

You need to manually fire the trackPageview on every page load:

   ...the rest of the body here...

...also, be sure to modify the Analytics snippet not to do '_trackPageview' automatically.

Some people recommend placing it in a page:change handler, which I think is a very naive solution that should be avoided, since it means that older browsers will not record visits to Analytics.

Using turbolinks outside Rails

Turbolinks is simply two things:

You can use the JavaScript script on your non-Rails project, just be aware of the Referrer caveat.

jQuery integration

First of all, you're most likely using jQuery. Go check out jQuery.turbolinks, which hijacks all $(function() { ... }) calls to load every time the page loads via Turbolinks.


Add a comment