Skip to content

Instantly share code, notes, and snippets.

@clupasq
Last active October 26, 2016 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clupasq/26a0f7b25f030f25b689fbcef93cda4d to your computer and use it in GitHub Desktop.
Save clupasq/26a0f7b25f030f25b689fbcef93cda4d to your computer and use it in GitHub Desktop.
// 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);
} else {
callback && callback();·
}
};
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();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment