Skip to content

Instantly share code, notes, and snippets.

@markselby
Last active February 19, 2020 10:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markselby/7209751 to your computer and use it in GitHub Desktop.
Save markselby/7209751 to your computer and use it in GitHub Desktop.
Load GitHub Gists asynchronously and optionally specify which file to show. This allows you to keep related files in a single gist but show them individually on your pages. The async loading prevents your page rendering from stalling.
function loadGists() {
var els = $('code[gist]'), gists = {}, code = [], stylesheets = [];
// Get elements referencing a gist and build a gists hash referencing the elements that use it
els.each(function(idx, rawEl) {
var el = $(rawEl), gist = el.attr('gist');
rawEl.gist = gist;
rawEl.file = el.attr('file');
gists[gist] = gists[gist] || { targets: [] };
gists[gist].targets.push(el);
});
// Load the gists
$.each(gists, function(name, data) {
$.getJSON(name + '?callback=?', function(data) {
var gist = gists[name];
gist.data = data;
// Only insert the stylesheets once
if(stylesheets.indexOf(gist.data.stylesheet) < 0) {
stylesheets.push(gist.data.stylesheet);
$('head').append('<link rel="stylesheet" href="https://gist.github.com' + gist.data.stylesheet + '" />');
}
gist.files = $(gist.data.div).find('.gist-file');
gist.outer = $(gist.data.div).first().html('');
// Iterate elements refering to this gist
$(gist.targets).each(function(idx, target) {
var file = target.get(0).file;
if(file) {
var o = gist.outer.clone();
var c = '<div class="gist-file">' + $(gist.files.get(gist.data.files.indexOf(file))).html() + '</div>';
o.html(c);
target.replaceWith(o);
}
else {
target.replaceWith(gist.data.div);
}
});
});
});
}
// Load them on document ready
$(loadGists);
<!-- Note the .json at the end of the gist URL -->
<p>Add some markup like this :</p>
<code gist="https://gist.github.com/markselby/7209751.json" file="sample-markup.html"></code>
<p>Here's the javascript that does the work.</p>
<code gist="https://gist.github.com/markselby/7209751.json" file="async-gists.js"></code>
<p>Bingo! I now have a self referencing Gist :-)</p>
@aliharis
Copy link

Hi Mark. Thanks for the solution. Works like a charm. Here's something you might wanna fix. gists.data.stylesheet return the complete url to the stylesheet (including gist.github.com). We have to remove https://gist.github.com from line 19.

@razor-x
Copy link

razor-x commented May 16, 2015

I've created a Bower package based on this: https://github.com/razor-x/gist-async

Original fork for reference: https://gist.github.com/razor-x/8288761

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