Turbolinks is a feature that will be a part of Rails 4. It can also be enabled in Rails 3.2 with the steps described in this post.
Why use Turbolinks
When using Turbolinks, only the page body and the title are retrieved from the server using AJAX, while the common parts of the page stay the same making the page load time shorter. The browser does not have to process the JS and CSS files again when loading a new page making the whole process faster.
More details can be found on the Turbolinks Github page
Steps to enable Turbolinks
- add it to gemfile
- add to application.js
//= require turbolinks
- install the gem with bundler
$ bundle install
Instead of document.ready, the event page:change is triggered when the page is loaded. This means that the code residing in a document ready block
$ -> # code that should be triggered
will not get run unless some changes are made.
There are two cases to consider triggering different events:
- user loads the page for the first time -> document.ready
- user loads a new page from navigation -> AJAX page load -> page:change
In most cases you'd want your original JS code to be run after the page is loaded in either one of the cases.
One way to resolve this problem is with jquery-turbolinks gem
but I did the minor changes required manually and moved all JS to be bound to the page:change event
$(document).on 'page:change', ->
and updated document ready to trigger a page:change event:
$ -> $(document).trigger 'page:change'
I also made some changes to Google Analytics to get the event triggered and added
under the page:change event.
Turbolinks is a nice trick to make page loads faster with few downsides. New browsers work faster than before while older browsers will fallback to the normal way of loading the page.