Skip to content

Instantly share code, notes, and snippets.

@saket28
Forked from Lobstrosity/tumblrGists.js
Created March 19, 2012 01:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save saket28/2090021 to your computer and use it in GitHub Desktop.
Save saket28/2090021 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 +
'.js"></scr' + 'ipt>');
}
};
// One call to embedNextGist to get the ball rolling.
embedNextGist();
@slezica
Copy link

slezica commented May 20, 2012

Brialliant idea! I totally copied it!

Seriously now, I think I came up with a more readable version. Give it a look if you're interested!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment