Using Turbolinks and jQuery dataTables in Rails 5
Turbolinks can enhance the performance of your web application by ‘hot swapping’ the <body>
tag using Ajax every time you click to a new page. It’s a great idea and clean implementation, however, any libraries written to initialize objects using the $( document ).ready()
in jQuery can run into issues. This is because the page (i.e. document) itself only loads once—the rest of the ‘clicks’ are being performed using Ajax.
The jQuery library dataTables utilizes the conventional document-ready scheme to initialize a data table. So with Turbolinks enabled, it gets initialized on the first page load, but not on subsequent navigation clicks. Therefore, when returning to the table, the DOM doesn’t know that your table is using dataTables.
There are a few workarounds, the most promising from How To Upgrade to Turbolinks 5 on GoRails, but the compatibility coffee script that automagically makes everything work appears to have been removed from the Turbolinks repository. But for this isolated application, the integration isn’t that hard, you just need to tap into the turbolinks:load
event. Here’s how I did it:
-
Make sure
gem 'turbolinks', '~> 5.2.0'
andgem 'jquery-turbolinks'
are in your Gemfile. -
Add all the requires to
application.js
(note: I’m using Bootstrap)://= require jquery.dataTables.js
//= require dataTables.bootstrap4.js
//= require dataTables.responsive.js
//= require responsive.bootstrap4.js
//= require jquery.turbolinks
//= require turbolinks
-
Initialize a data table (
id = ‘data-table’
) either in your table’s view, or in a<scripts>'
tag at the bottom ofapplication.html.erb:
$( document ).on('turbolinks:load', function() {
$('#data-table').DataTable();
});
Also note, I am passing defaults through the dataTables.bootstrap.js
file at the line starting with $.extend( true, DataTable.defaults, {
.
Recent Comments
Archives
- April 2023
- January 2023
- November 2022
- May 2022
- March 2022
- January 2022
- December 2021
- April 2021
- December 2020
- October 2020
- August 2020
- July 2020
- March 2020
- February 2020
- January 2020
- December 2019
- November 2019
- October 2019
- January 2019
- December 2018
- November 2018
- August 2018
- July 2018
- April 2018
- March 2018
- November 2017
- October 2017
- February 2017
- October 2016
- August 2016
- July 2016
- November 2015
- October 2013
- February 2013
- January 2013
- August 2012
- July 2012
- June 2012
- May 2012
- April 2012
- February 2012
- December 2011