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:

  1. Make sure gem 'turbolinks', '~> 5.2.0' and gem 'jquery-turbolinks' are in your Gemfile.

  2. 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
  3. Initialize a data table (id = ‘data-table’) either in your table’s view, or in a <scripts>' tag at the bottom of application.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, {.