Michael Cordell's Blog

Rails 4, Turbolinks, and jQuery

If you have a Rails 4 project with malfunctioning jQuery the culprit is likely a new feature in Rails 4 called turbolinks. Turbolinks attempts to speed response times by not reloading the header (in fact the whole page) each time a new request is made. Instead, the body of the page is replaced using ajax and json. The idea here is that it cuts down on the overhead of loading and parsing the Javascript and style sheets each time a new page is loaded. However, apparently this feature is not every popular, as an analysis of the 2013 Rails Rumble showed that the majority of participants turned off turbolinks.

A likely problem, and one that I ran into on a Rails 4 project, is that the jQuery is not functional until the page is loaded once and then refreshed. This is because turbolinks often breaks javscript libraries such as jQuery. Many library devs are wising up to this and fixing these breaks. However, for now we have to work around these issues. In the case of jQuery the fix is straight forward.

  1. Add this to your Gemfile:
gem 'jquery-turbolinks'
  1. In your application.js, add this after your jQuery requires and before your turbolink require. For example:
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require jquery.turbolinks
//= require turbolinks
  1. Restart your application server and you should now have properly functioning jQuery.