Skip to content

Instantly share code, notes, and snippets.

@johnrengelman
Forked from saket28/tumblrGists.js
Last active May 5, 2020 21:37
Show Gist options
  • Save johnrengelman/8055533 to your computer and use it in GitHub Desktop.
Save johnrengelman/8055533 to your computer and use it in GitHub Desktop.
var gistPrefix = 'https://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 = $('a.gist').map(function(n, a) {
a = $(a);
var href = a.attr('href');
// Only return the mapping if a valid a exists in the a.
if (href.indexOf(gistPrefix) == 0) {
return {
a: a,
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.a.replaceWith(gistDiv);
embedNextGist();
};
};
body.append('<scr' + 'ipt src="' + gistPrefix + gist.id +
'"></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