DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

JavascriptTwitter BootstrapDatatables

Javascript Problem Overview


When using the Bootstrap integration for DataTables, I see the following error in the console:

Uncaught TypeError: Cannot read property 'defaults' of undefined (dataTables.bootstrap.js:20)

This causes the pagination controls to not have styles on them.

I can see that in the factory initialization, the following code needs to run:

factory( jQuery, jQuery.fn.dataTable );

However, jQuery.fn.dataTable is returning undefined.

Javascript Solutions


Solution 1 - Javascript

The problem is that dataTable is not defined at the point you are calling this method.

Ensure that you are loading the .js files in the correct order:

<script src="/Scripts/jquery.dataTables.js"></script>
<script src="/Scripts/dataTables.bootstrap.js"></script>

Solution 2 - Javascript

I got the same error, I'm using laravel 5.4 with webpack, here package.json before:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    ...
    ...
  },
  "dependencies": {
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I had to move jquery and datatables.net npm packages under one of these "dependencies": {} or "devDependencies": {} in package.json and the error disappeared, after:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I hope that helps!

Solution 3 - Javascript

<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>

Add Defer to the end of your Script tag, it worked for me (;

Everything needs to be loaded in the correct order (:

Solution 4 - Javascript

var datatable_jquery_script = document.createElement("script");
datatable_jquery_script.src = "vendor/datatables/jquery.dataTables.min.js";
document.body.appendChild(datatable_jquery_script);
setTimeout(function(){
    var datatable_bootstrap_script = document.createElement("script");
    datatable_bootstrap_script.src = "vendor/datatables/dataTables.bootstrap4.min.js";
    document.body.appendChild(datatable_bootstrap_script);
},100);

I used setTimeOut to make sure datatables.min.js loads first. I inspected the waterfall loading of each, bootstrap4.min.js always loads first.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyan KohnView Question on Stackoverflow
Solution 1 - JavascriptRyan KohnView Answer on Stackoverflow
Solution 2 - JavascriptAlan EliasView Answer on Stackoverflow
Solution 3 - JavascriptDonaldView Answer on Stackoverflow
Solution 4 - JavascriptEugene OcaView Answer on Stackoverflow