Aug 25, 2014

Few Hacks for Rails and Turbolinks

blogpost cover image
Ever since 4.0, Rails comes bundled with the Turbolinks gem. It’s a nice way of reducing page load times – instead of reloading the page entirely, recompiling the CSS and Javascript between each page change, it just replaces the body and the head title. This of course can create trouble at times.

Why so Turbo?

Maintaining the session state is a neat thing, but you have to be extra careful about memory leaks. The more jQuery you use, the higher the probability of scripts being loaded twice (or not at all). The most common mistake for begginers is $(document).ready(), which of course doesn’t fire anymore, since the page isn’t being reloaded anymore. Instead, it’s better to use $(document).on("page:load");. But that doesn’t solve everything either.

The gem we deserve, but not the one we need

If, for example, you would want to disable turbolinking on one specific anchor, simply add the data-no-turbolink class to it. If you have more links that need to ignore turbolinking, just put them in a div with the same class and voila! Done. Reversely, if you do want to redirect through turbolinking, the gem comes packed with a redirect_via_turbolinks_to helper method, which can be a lot quicker.

jQuery? but of course

Most problems with jQuery and Turbolinks can be solved simply by using the brilliantjQuery.Turbolinks gem. It causes $(document).ready() functions to still launch even when redirecting through Turbolinks.

Not as simple as it seems

Sometimes, even if you try to use all the hacks, and they still don’t work, you have do go a bit deeper. I ran into a problem combining Turbolinks with Addthis script – the script didn’t seem to load. The problem was that Addthis was setting some window properties that weren’t getting cleared – because of the aforementioned session maintenance. I didn’t want to disable turbolinking just to fix a social media sharing bar, so I had to work out something unorthodox. We managed to solve the problem by clearing the properties one by one through a custom function, then getting the script and and initializing it manually. Here’s the code that saved the day:

addthisInit = function() {

  // Remove all global properties set by addthis, otherwise it won't reinitialize
  if(window.addthis) {
       window.addthis = null;
        window._adr = null;
        window._atc = null;
        window._atd = null;
        window._ate = null;
        window._atr = null;
        window._atw = null;
    window.addthis_share = null;

  // Finally, load addthis
  $.getScript("", function(){
    // addthis.init();

  // });

After that, all that was left to do was putting //= require addthis in the [layout].js file and it was done.

I hope this little fix, as well as the information on the Turbolink gem itself will save you the pain of figuring this out for yourselves. As always, questions, feedback and comments are welcome. Cheers!