Skip to content

Instantly share code, notes, and snippets.

@clupasq
Last active October 26, 2016 06:46

Revisions

  1. clupasq revised this gist Oct 26, 2016. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions dynamically_add_datatables.js
    Original file line number Diff line number Diff line change
    @@ -8,6 +8,8 @@ var addJqueryIfNotPresent = function(callback){
    scr.src = 'https://code.jquery.com/jquery-2.2.4.min.js';
    scr.onload = function(){ callback && callback(); };
    document.head.appendChild(scr);
    } else {
    callback && callback();·
    }
    };

  2. clupasq created this gist Oct 26, 2016.
    47 changes: 47 additions & 0 deletions dynamically_add_datatables.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    // Run this script on any page to load the DataTables library
    // (https://datatables.net/)
    // and add DataTable functionality to all tables

    var addJqueryIfNotPresent = function(callback){
    if(!window.jQuery){
    var scr = document.createElement('script');
    scr.src = 'https://code.jquery.com/jquery-2.2.4.min.js';
    scr.onload = function(){ callback && callback(); };
    document.head.appendChild(scr);
    }
    };

    var addDatatablesLibrary = function(callback){
    var css = document.createElement('link');
    css.rel = 'stylesheet';
    css.href = 'https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css';
    document.head.appendChild(css);
    var scr = document.createElement('script');
    scr.src = '//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js';
    scr.onload = function(){ callback && callback(); };
    document.head.appendChild(scr);
    };

    // Tables must be well formed (with thead and tbody) in order for
    // DataTable to work
    var prepareTables = function() {
    var tables = Array.prototype.slice.call(document.querySelectorAll('table'));
    tables.forEach(function(t){
    var firstRow = t.querySelector('tr');
    if(!firstRow) {return;}
    var thead = t.querySelector('thead');
    if (thead) {return;}
    thead = document.createElement('thead');

    firstRow.parentElement.removeChild(firstRow);
    thead.appendChild(firstRow);
    t.insertBefore(thead, t.firstchild);
    });
    };

    prepareTables();
    addJqueryIfNotPresent(function(){
    addDatatablesLibrary(function(){
    $('table').DataTable();
    });
    });