Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Last active August 29, 2015 13:58
Show Gist options
  • Save brennanMKE/10001733 to your computer and use it in GitHub Desktop.
Save brennanMKE/10001733 to your computer and use it in GitHub Desktop.
Embed Gists
$(function() {
var gistPrefix = 'https://gist.github.com/';
var embedGists = function() {
$('a[href^="' + gistPrefix + '"]').each(function(index, anchor) {
var href = $(anchor).attr('href');
var gistId = href.substring(gistPrefix.length);
var url = gistPrefix + gistId + '.json?callback=?';
$.getJSON(url, function(gistData) {
var cssUrl = gistPrefix + gistData.stylesheet;
if ($('link[href="' + cssUrl + '"]').length == 0) {
$('head').append('<link rel="stylesheet" href="' + cssUrl + '" type="text/css" />');
}
$(anchor).replaceWith(gistData.div);
});
});
};
var infiniteScrollUpdated = function() {
embedGists();
};
embedGists();
// export behavior for infinite scroll
var myGitHub = {};
myGitHub = infiniteScrollUpdated;
window.myGitHub = myGitHub;
});
@brennanMKE
Copy link
Author

Embed Gists

Embedding a Gist in your blog or any web page is as easy as placing an anchor tag with an href value pointing to the Gist. This script will replace that tag with the markdown returned from a GitHub service that makes it easy to embed Gists, including the necessary CSS.

Infinite Scroll

On my blog I use infinite scroll to bring in more blog posts as the bottom is reached. When that happens the infinite scroll script is set up to call this script to embed any Gists which are referenced in newly loaded blog posts.

Fallback Support

If embedding the Gists does not work for whatever reason the link will still be there which allows users to view the Gist directly.

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