Get Rid of that DataTables Loading Glitch

nathanwells

Add a loading spinner to DataTables without AJAX and get rid of that glitch!

If you've ever used DataTables you've probably witnessed that double-loading glitch where the user first sees the HTML table load with all the data, and then the table is re-formatted by DataTables and re-sorted. It looks bad. Especially if you're loading a large table:

What a user normally sees when you use DataTables with a plain HTML table

But what can do you about it? For a long time the only solution I ever came across was to bring your data into the DataTable via AJAX. But it turns out you can have a loading spinner with a normal HTML table as well! All you need is a little jQuery magic!

A DataTable with a nice loading spinner and no glitch!

Doesn't that look so much better?

The trick is simple. You hide the HTML table and instead show the spinner (in this case a simple Bootstrap spinner). And then instead of just loading the DataTable, you detect when the DataTable is finished rendering and then hide the spinner and change the id of the table so that it is no longer hidden:

.on( 'draw.dt', function () { /* do whatever you want here */ } )

But it's probably easier to just see it in action! You can view a working CodePen here: Bootstrap 4 Responsive DataTable with Loading Spinner

I'd love to hear if this was helpful to you!

Like what you read?