'How to make DataTables work with Turbolinks 5?

I'm working on something in Ruby (2.7.3) on Rails (6.1.3). I got a task to setup jQuery Datatable. No problem there:

<script>

$(document).ready( function () {
    $('#stakingTable').DataTable();
} );

</script>

I have my jQuery imports at the top of the html.erb file as such:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" type="text/javascript" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<link rel="stylesheet" href="//cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">

<script src="//cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>

In this path, app/javascript/packs/application.js, I have the following imports:

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"

Rails.start()
Turbolinks.start()

Now, when given this task to implement DataTable, I noticed that I need to refresh my page, once, before it loads the DataTable. I checked my console, before reload, and got the following error:

Uncaught ReferenceError: $ is not defined
    at <anonymous>:3:1
    at o.assignNewBody (turbolinks.js:604:1)
    at o.replaceBody (turbolinks.js:542:1)
    at turbolinks.js:535:1
    at o.e.renderView (turbolinks.js:495:1)
    at o.render (turbolinks.js:533:1)
    at Function.e.render (turbolinks.js:493:1)
    at t.renderSnapshot (turbolinks.js:690:1)
    at t.render (turbolinks.js:686:1)
    at r.render (turbolinks.js:940:1)

The answer my mentor gave me had something to do with Turbolinks, and how it loads the page too fast for the jQuery to be applied. So I had a look around and saw that this seemed to be a common solution:

<script>

$(document).on(;'turbolinks:load' function () {
    $('#stakingTable').DataTable();
} );

</script>

However, this does nothing for me. Still the same error in the console, as mentioned above. I've looked at some of the Turbolinks documentation here: https://github.com/turbolinks/turbolinks, and I have tried playing around with different turbolinks:before-cache and other features, and yet, nothing works.

Is there something I am missing? If anyone could help, I would be very thankful.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source