Skip to content

Instantly share code, notes, and snippets.

@webarthur
Last active September 4, 2016 17:43
Show Gist options
  • Save webarthur/601c95c3e4319cee3301fef780d8a4bd to your computer and use it in GitHub Desktop.
Save webarthur/601c95c3e4319cee3301fef780d8a4bd to your computer and use it in GitHub Desktop.
Dynamically embedding Gists
document.addEventListener("DOMContentLoaded", function(event) {
document.write = function (code) {
var gistURL, div, a, style;
// create a <div> element to search gist url
div = document.createElement('div')
div.innerHTML = code
// get gist url from code
if(a = div.querySelector( "div.gist-meta a" )) {
gistURL = a.getAttribute('href')
}
// search for <script> tag and update gist code
if(gistURL) {
var gistID = gistURL.replace(/\/raw(.)*/, '').replace(/^(.)*gist.github.com\/([^\/]+)\//, '');
document.querySelectorAll('script').forEach(function (item) {
var scriptURL = item.getAttribute('src');
if(scriptURL && scriptURL.match(new RegExp('^(.)*gist.github.com\/([^\/]+)\/'+gistID))) {
item.outerHTML = code;
}
});
}
// include CSS
else if (!document.write.cssIncluded){
document.write.cssIncluded = 1;
style = document.createElement('div')
style.innerHTML = code
document.getElementsByTagName("head")[0].appendChild(style.childNodes[0]);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment