Last active
February 5, 2018 17:15
-
-
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
This file contains hidden or 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.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]); | |
} | |
} | |
})(); |
This file contains hidden or 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
(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