Skip to content

Instantly share code, notes, and snippets.

@jad
Last active August 29, 2015 14:05
Show Gist options
  • Save jad/1e0c677bfa7b464c142b to your computer and use it in GitHub Desktop.
Save jad/1e0c677bfa7b464c142b to your computer and use it in GitHub Desktop.
var gistPrefix = 'http://gist.github.com/',
// Cache document.write so that it can be restored once all Gists have been
// embedded.
cachedWrite = document.write,
body = $('body'),
// Map each p.gist to an object that contains the paragraph to be replaced
// and the Gist's identifier.
gists = $('p.gist').map(function(n, p) {
p = $(p);
var a = $('a', p),
href = a.attr('href');
// Only return the mapping if a valid a exists in the p.
if (a.length && href.indexOf(gistPrefix) == 0) {
return {
p: p,
id: href.substring(gistPrefix.length)
};
}
else {
return undefined;
}
}).get(),
embedNextGist = function() {
// If there are no more Gists to embed, restore document.write.
if (gists.length == 0) {
document.write = cachedWrite;
}
else {
var gist = gists.shift();
// The Gist javascript file consists of a call to document.write to
// write the stylesheet link element and a second call to
// document.write to write the div containing the marked up Gist.
// So, override document.write to catch the first call. And inside
// that override, override document.write again to catch the second
// call.
document.write = function(styleLink) {
// On my Tumblr page, I include GitHub's Gist stylesheet in my
// overall page template so nothing happens here. If you don't
// want to do that, you could do something here like
// $('head').append(styleLink);
document.write = function(gistDiv) {
// Replace the original paragraph with the formatted div
// written by the Gist javascript file.
gist.p.replaceWith(gistDiv);
embedNextGist();
};
};
body.append('<scr' + 'ipt src="' + gistPrefix + gist.id +
'.js"></scr' + 'ipt>');
}
};
// One call to embedNextGist to get the ball rolling.
embedNextGist();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment