Skip to content

Instantly share code, notes, and snippets.

@JeanSebTr
Last active February 5, 2018 17:15
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JeanSebTr/4138162 to your computer and use it in GitHub Desktop.
Save JeanSebTr/4138162 to your computer and use it in GitHub Desktop.
Async load of Github's gists without jquery in 31 lines of code
document.getElementsByClassName && (function(){
var _URL = /(https?:\/\/gist.github.com\/[^?#]+)(\?file=([a-z0-9_.-]+))?/i;
var gists = document.getElementsByClassName('gist');
function embed(url, i, tag) {
window['embed_gist_'+i] = function(gist) {
var tmp = document.createElement('div');
tmp.innerHTML = gist.div;
tag.parentNode.replaceChild(tmp.firstChild, tag);
var css = document.getElementsByClassName('gist_css');
for(var i=0; i<css.length; i++) {
if(css[i].href == gist.stylesheet) {
return;
}
}
css = document.createElement('link');
css.rel = 'stylesheet';
css.href= gist.stylesheet;
css.className = 'gist_css';
document.head.appendChild(css);
};
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
}
for(var i=0; i<gists.length; i++) {
var parts = _URL.exec(gists[i].href);
if(parts) {
var url = parts[1]+'.json?callback=embed_gist_'+i;
if(parts[3]) { // file
url += '&file='+parts[3];
}
embed(url, i, gists[i]);
}
}
})();
(function(){
var gists = document.getElementsByTagName('gist');
function embed(id, file, i, tag) {
window['embed_gist_'+i] = function(gist) {
var tmp = document.createElement('div');
tmp.innerHTML = gist.div;
tag.parentNode.replaceChild(tmp.firstChild, tag);
};
var url = 'https://gist.github.com/'+id+'.json?callback=embed_gist_'+i;
if(file) {
url += '&file='+file;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
}
if(gists.length) {
var css = document.createElement('link');
css.rel = 'stylesheet';
css.href= 'https://gist.github.com/stylesheets/gist/embed.css';
document.head.appendChild(css);
}
for(var i=0; i<gists.length; i++) {
var id = gists[i].getAttribute('data-id');
var file = gists[i].getAttribute('data-file');
if(id) {
embed(id, file, i, gists[i]);
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment