Last active
October 26, 2016 06:46
-
-
Save clupasq/26a0f7b25f030f25b689fbcef93cda4d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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