Skip to content

Instantly share code, notes, and snippets.

@benjamine
Forked from mathewbyrne/README.mdown
Created May 30, 2011 16:04
Show Gist options
  • Save benjamine/999085 to your computer and use it in GitHub Desktop.
Save benjamine/999085 to your computer and use it in GitHub Desktop.
An asynchronous method for embedding gists in an HTML document using jQuery.

A quick jQuery plugin for asynchronously embedding a gist in an HTML document.

There are a couple of ways to use it. The simpler way is replacing all Gist links in document by their embedded version:

<script>$($.gist);</script>

All links that point to a gist, or gist file will be replaced by the corresponding embedded gist, or gist file.

Gist link replacement can also be called on a container element:

<script>$('#main').gist();</script>

A jQuery selector can be used to filter anchors to replace:

<script>$('a.gist-embed').gist();</script>

By default gist id and file is obtained from anchor urls, but they can be specified as arguments:

<script>$('a#mygist').gist(999085);</script>
<script>$('a#mygist').gist(999085, 'README.mdown');</script>

Going further gist id and file can be provided in an object argument:

<script>$('a#mygist').gist({ id: 999085 });</script>
<script>$('a#mygist').gist({ id: 999085, file: 'README.mdown'});</script>

And as functions too:

<script>$('a.gist').gist({ id: function(){ this.attr('data-gistid') });</script>
<script>$('a.gist').gist({ id: function(){ this.attr('data-gistid') }, file: function(){ this.attr('data-gistfile') }});</script>

Finally, there is a direct method that will insert a gist into the current position in the document:

<script>$.gist(999085)</script>
<script>$.gist(999085, 'README.mdown')</script>

A couple of notes:

  1. This works asynchronously, which has the advantage of not blocking the loading of a page. This has the slight disadvantage of "popping" in after it has loaded, but this could be alleviated with animations etc. by creating an event handler for the gistloaded event.

  2. As mentioned, after the gist has been loaded and inserted into the DOM, a gistloaded event is triggered on the newly created DOM object. This is to facilitate adding any custom behaviours after the gist has loaded. Potentially this could be things like animations, attaching events etc.

  3. Currently if you specify an element to 'receive' the gist, that element is replaced, so be cautious of using it again.

(function ($) {
var count = 1,
stylesheets = {},
gistUrlRegex = new RegExp('^(https?://)?gist.github.com/([0-9]+)(#file_(.*))?$');
$.gist = function (id, file, placeholder) {
if (!id || id === $) {
// no arguments, replace all anchors in document
$(document).gist();
} else {
placeholder = placeholder || ['gist', id, count++].join('-');
$('<div />', { 'id': placeholder }).appendTo('body').gist(id, file);
}
};
$.gist.url = function (id, file) {
var $this;
var https = false;
if (!id && ($this = $(this)).is('a')) {
// no id specified, get from anchor href
var match = gistUrlRegex.exec($this.attr('href'));
if (match) {
https = match[1] == 'https://';
id = match[2];
file = match[4] || file;
}
} else if (typeof id == 'object') {
file = typeof id.file == 'function' ? id.file.apply(this) : id.file;
id = typeof id.id == 'function' ? id.id.apply(this) : id.id;
}
if (!id) {
return null;
}
var url = (https ? 'https' : 'http') + '://gist.github.com/' + id + '.json?';
if (file) {
url += 'file=' + file + '&';
}
url += 'callback=?';
return url;
};
$.fn.gist = function (id, file) {
if (!id && !this.is('a')) {
// container and no parameters, call on contained anchors
return this.find('a').gist();
}
for (var i = 0, l = this.length; i < l; i++) {
var self = this[i];
var url = $.gist.url.apply(self, arguments);
if (url) {
$.ajax(url, {
dataType: 'json',
context: self,
success: function (json) {
// embed gist
$(json.div).replaceAll(this).trigger('gistloaded', json);
// add stylesheet
if (json.stylesheet && !stylesheets[json.stylesheet]) {
if (!$(document.head).find('link[rel=stylesheet]').filter(function () { return this.href == json.stylesheet; }).length) {
$(document.head).append('<link rel="stylesheet" href="' + json.stylesheet + '"/>');
}
stylesheets[json.stylesheet] = json.stylesheet;
}
}
});
}
}
return this;
};
})(jQuery);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>$.gist test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="gist.js" type="text/javascript"></script>
</head>
<body>
<h1>$.gist demo</h1>
<p>This demo contains some gist links that will be converted to embedded gist on document load</p>
<a href="https://gist.github.com/999085#file_README.mdown">view README</a>
<p>Here's a $.gist example html:</p>
<a href="https://gist.github.com/999085#file_test.html">view html</a>
<script type="text/javascript">
$($.gist); // replace gist links by embedded gists
</script>
</body>
</html>
@ankitrox
Copy link

Dude this is just awesome way to embed gist in a webpage without hitting performance. 👍
Thanks friend.

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