Skip to content

Instantly share code, notes, and snippets.

@mathewbyrne
Created May 22, 2010 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mathewbyrne/409808 to your computer and use it in GitHub Desktop.
Save mathewbyrne/409808 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. First is the direct method that will insert it into the current position in the document:

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

Secondly, there is a more jQuery oriented method:

<div id="placeholder"></div>
<script>$('#placeholder').gist(409808);

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. The default gist stylesheet will not be included via this method. The URL of the stylesheet does get passed in via the 'stylesheet' key of the returned JSON, so again if desired you could catch the gistloaded event and pull the stylesheet out of the JSON object.

  3. 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.

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

  5. A single file from the gist can be included by specifying the second parameter, the file name as a string: $.gist(409808, 'gist.js').

(function ($) {
var count = 1;
$.gist = function (id, file, placeholder) {
placeholder = placeholder || ['gist', id, count++].join('-');
$('<div />', { 'id': placeholder }).appendTo('body').gist(id, file);
};
$.gist.url = function (id, file) {
var url = 'http://gist.github.com/' + id + '.json?callback=?';
if (file) {
url += '&file=' + file;
}
return url;
};
$.fn.gist = function (id, file) {
var self = this,
url = $.gist.url.apply(this, arguments);
$.getJSON(url, function (json) {
$(json.div)
.replaceAll(self)
.trigger('gistloaded', json);
});
return this;
};
})(jQuery);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>$.gist test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="gist.js" type="text/javascript"></script>
</head>
<body>
<script>$.gist(409808)</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment