Turbolinks and Other Libraries

Written by on Nov 27 2012

As we all know by now Turbolinks replaces everything under the body tag when loading a new page. This is pretty good, but it does create a problem when you’re using another javascript library that magically adds something to the body tag.

In my example I was using the jQuery-UI Datepicker. It took me a little while to figure out that the reason the Datepicker no longer worked was because the divs that make up the date picker are only added once. If you’re using Turbolinks (and if you’re not now, you will be soon as it’s part of Rails 4) then you are almost certainly listening to the “page:change” event and initializing some of your javascript when it’s fired. The solution to our Datepicker problem is simply to call

$.datepicker.initialized = false

This will tell jQuery-UI that it has to add those dom elements again.

At this point you might be thinking “Turbolinks is stupid and should do that for us.” Here’s why that thinking is wrong: Turbolinks does one, very specific thing; it ajaxes links and replaces (and caches) the current body content with the body content that gets returned from the server. Knowing that that’s what it does, it is our responsibility to make sure the other libraries we use (or our own code) plays nicely with that paradigm. If we want to avoid that paradigm we can choose not to use Turbolinks, perhaps using Pjax or nothing instead.

I think in this case the jQuery-UI library could be smarter and rather than maintain a variable they could actually check to see if their dom elements exist (I’m guessing they check the variable for performance reasons).


Hi I'm Steven,

I wrote the article you're reading... I lead the developers, write music, used to race motorcycles, and help clients find the right features to build on their product.

Get Blog Updates