The goal of Turbolinks is to make web pages load faster. The first one will load like usual. Then, when the visitor clicks on a link, the next page is loaded through an asynchronous call. The server sends back the HTML, and Turbolinks updates the page’s
body with the new content, leaving the
head untouched. Your big application.js is not fetched nor parsed again, which saves some precious milliseconds before everything is rendered.
Version 3 of Turbolinks adds the possibility of updating any HTML tag of your choice, instead of
We’ll use a simple Comment resource with standard CRUD as an example, and progressively modify the code to take advantage of Turbolinks 3 for the C(reate) part.
Start by creating a new Rails app:
Use the Turbolinks master branch: (until 3.0 is officially out)
And don’t forget to
in the project’s folder.
First, generate the resource:
Now, instead of using a separate page to create a new comment, we will create it directly on the comments index page.
In the comments index view, replace the
link_to 'New comment' with the comment form:
Then add the new comment instance in the controller:
If you try to create a new comment now, it will redirect to the
show action. Let’s change that in the controller:
Now when we submit a new comment, it redirects to the index. But the whole page is reloaded, without any Turbolinks benefit. To change that, we will submit our form with an asynchronous call:
Note that all content is still refreshed, but Turbolinks now only updates the
<body> part. This is essentially what Turbolinks 2 brings to the table.
As a bonus, you can see that Turbolinks displays a progress bar of its own at the top of the page during the Ajax request.
To benefit from the Turbolinks 3 main new feature, partial updates, we just have to set an id for the HTML tag we want to update:
And add the new
change parameter to the
redirect_to call in our controller:
That’s it! When we create a new comment, the
You may have noticed that the submit generates 2 requests: a POST for the
create action, and a GET for the
index action, just after the redirect.
Version 3 is set to be officially released alongside Rails 5 this fall 2015. While the current master warns that specs might still change, it’s already fairly useable with Rails 4.
The gem’s README has many more capabilities listed. You can of course update multiple tags at once, hook to page events, change the progress bar style, or force tags to update (or not) thanks to new data attributes.
There is a companion demo app for this article on Github. Feel free to browse the code and experiement with your own changes.