Using DataTables in Publish

Thank you @porterhaus for your solution :).
I’ve added a couple of things that I’m sharing here:

  • With a dirty hack, I think I’ve managed to get the initialization right… 100% of the time?
  • I added styling the table on page change, which was not on the original solution. So now your tables are turned into a DataTable even if you navigate through your site.

Here is all that is needed:

(() => {
    var script_jquery = document.createElement('script');
    script_jquery.src = '//code.jquery.com/jquery-3.6.0.min.js';
    script_jquery.setAttribute('type', 'text/javascript');
    script_jquery.setAttribute('charset', 'utf8');
    document.getElementsByTagName("body")[0].appendChild(script_jquery);

    var link_datatables = document.createElement('link');
    link_datatables.setAttribute('rel', 'stylesheet');
    link_datatables.setAttribute('href', '//cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css');
    link_datatables.setAttribute('type', 'text/css');
    document.getElementsByTagName('body')[0].appendChild(link_datatables);
    
    var script_datatables = document.createElement('script');
    script_datatables.src = '//cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js';
    script_datatables.setAttribute('type', 'text/javascript');
    script_datatables.setAttribute('charset', 'utf8');

    // Nasty thing we need to make sure DataTables is loaded AFTER jQuery
    setTimeout(() => {
        document.getElementsByTagName('body')[0].appendChild(script_datatables)},
        100
    )

    /**
     * Checks that both jQuery and DataTable are loaded to run `callback`
     */
    function checkReady (callback) {
        if (window.jQuery && $('').DataTable) {
            callback(jQuery);
        }
        else {
            window.setTimeout(function() { checkReady(callback); }, 20);
        }
    };

    /**
     * Styles every table in the page
     */
    function styleTable($) {
        $(() => $('table').DataTable());
    }

    // Starts polling
    checkReady(styleTable);

    // Styles tables on every page change
    window.app.on('navigated', () => checkReady(styleTable))

})();
3 Likes