Liz Banach Liz Banach - 10 months ago 189
jQuery Question

DataTables is not initializing properly in RequireJS project

I am utilizing the jQuery DataTables plugin for a project that uses RequireJS. I have loaded in the DataTables library and initialization script into the RequireJS

script, and added the appropriate element ID to the table in my template file. I cannot get DataTables to initialize. Seemingly, DataTables and RequireJS do not play well together. I am not seeing any error messages in the console regarding the code below, but it is still not working as intended.

NOTE: I have had many people suggest updating the name. To
, etc. None of these naming conventions have helped initialize DataTables.

Here is my initialization script:

require([""], function() {
$(function() {
// initialize DataTables

Here is my RequireJS configuration:

config: {
//Set the config for the i18n
//module ID
i18n: {
// Change this to en-us to use the strings in nls/en-us for example
locale: 'en-gb'
// "urlArgs": "ts=" + new Date().getTime(), // disable caching - remove in production
"baseUrl": "js/lib",
"paths": {
"app": "../app",
"jquery": "../lib/jquery-2-0-0.min",
"bootstrap": "../lib/bootstrap.min",
"backbone": "../lib/backbone-min",
"underscore": "../lib/underscore-min",
"text": "../lib/text.min",
"store": "../lib/store.min",
"loader": "../lib/spin.min",
"jquery-insertAtCaret": "../lib/jquery-insertAtCaret",
"splash-clearAndResetModal": "../lib/splash/clearAndResetModal",
"splash-utils": "../lib/splash/utils",
"splash-proofhq": "../lib/splash/proofhq",
"splash-config": "../config",
"": "//",
"datatables-js": "../lib/datatables-js"
wrapShim: false,
// Add dependancies to the libs
shim: {
// "enc-base64": {
// deps: ["sha256", "hmac-sha256"]
// }

Here is the Git repo if anyone is interested in playing around:

I am primarily working within the
folder. There you will see the
, and
where I am trying to get things to work.

Answer Source

I FINALLY was able to get this working. Allan from DataTables helped me out.

Basically, what was happening... there was not anything wrong with the DataTables initialization code as such (as odd as that may sound).

It was running, but at the point it is running, the table was not in the document. The #example selector found no elements and therefore, nothing happened. Then the template code in admin.js kicks in and puts the table into the DOM - but it happens too late!

What needed to change was initializing the DataTable AFTER the HTML table is in the DOM. This is done method in admin.js:

.done(function() {

The datatables-js.js file is not required since the loading of the HTML happens asynchronously. I hope this helps someone else with a similar project.