Last active
September 4, 2016 17:43
-
-
Save webarthur/601c95c3e4319cee3301fef780d8a4bd to your computer and use it in GitHub Desktop.
Dynamically embedding Gists
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
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