Skip to content

Instantly share code, notes, and snippets.

@firewalker06
Created January 12, 2012 03:23
Show Gist options
  • Save firewalker06/1598377 to your computer and use it in GitHub Desktop.
Save firewalker06/1598377 to your computer and use it in GitHub Desktop.
Embed Gist in Tumblr
// Source: http://inparens.tumblr.com/post/1362127815/embedding-github-gists-in-tumblr-posts
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.
// Modified the p selector, so you don't have to edit in HTML to add class
gists = $('p:contains("https://gist.github.com/")').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