Rails - DataTables (imported via CDN) shows 'Not a function' until refreshed
Rails - DataTables (imported via CDN) shows 'Not a function' until refreshed
cratag
Posts: 10Questions: 3Answers: 0
Hello I have imported DataTables via CDN. Here's the code I have in my genes.html.erb
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>
<script type="text/javascript">
document.addEventListener("turbolinks:load", function () {
$('#myTable').DataTable();
});
</script>
On first show up, the console logs:
VM8:3 Uncaught TypeError: $(...).DataTable is not a function
at HTMLDocument.<anonymous> (<anonymous>:3:17)
at Object../node_modules/turbolinks/dist/turbolinks.js.e.dispatch (turbolinks.js:75)
at r.notifyApplicationAfterPageLoad (turbolinks.js:994)
at r.visitCompleted (turbolinks.js:1007)
at r.complete (turbolinks.js:782)
at r.<anonymous> (turbolinks.js:812)
at turbolinks.js:862
after a refresh, it works perfectly.
but obviously I'd like it to work before I refresh.
I've tried some things with no avail. Here's my post on StackOverflow
If there's something else I can add, let me know
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
It would be worth looking to see where you're loading jQuery. This needs to be before DataTables. If it loads after, you would get an error like this.
Colin
It is loaded via webpacker in Rails 6.
and
a kind soul made a Jfiddle for me, when I asked for help: https://jsfiddle.net/bogatyr77/dxrmnw0g/1/
on first show, it returns the same error:
and works after first refresh.
I'm completely lost.
I'm using Ubuntu 20.04 - maybe that makes a difference?
This JFIDDLE sometimes works and some others doesnt
Seems like there is a timing issue with how you are loading the datatables.js in the
init()
function and when thedocument.ready()
function runs. I used settimeout() to introduce a slight delay before initializing Datatables.https://jsfiddle.net/sonzctye/1/
I'm not familiar with the method you are using in
init()
. But if there is a callback you can use when its complete then the settimeout delay would be unnecessary. This doesn't seem to be a Datatables specific issue as there doesn't seem to be an issue if the datatables.js is loaded normally as in this example:https://jsfiddle.net/sonzctye/2/
You might find suggestions on Stack Overflow or other resources.
Kevin
Well adding a timeout does the trick. Thank you very much.
It happened before I used the init() function - as someone helped me out in my Stack Overflow thread.
It might not be a DataTables issue, but it happens both in my Rails app and in the jsfiddles provided - so its weird.