Embedding Gists

When I was deciding how to handle code-snippet highlighting for this version of my blog, I looked at many options, ranging from server-side options to javascript highlighting libraries. Then I remembered that you can embed gists.

Using gists would not only give me syntax highlighting, but would also cause all of the snippets I share to be fully-versioned, git repositories, capable of being forked, edited, and shared.

Despite multiple problems with styling the various gist containers, I got the styling just about perfect for my needs. However, during the course of styling, I realized using the default embed code wasn’t going to cut it, since it was a single javascript include that stopped the page from loading until the external javascript file was loaded.

I was not willing to sacrifice page speed for the benefits of storing my code snippets as gists, so I whipped up a way to avoid the annoying blocking with jQuery.

Basically, the solution boils down to only including the unique identifier for each gist and looping through them after the page has loaded, replacing our dummy HTML element with the actual styled code.

Here’s an example of a dummy HTML element that would work. Notice the class of gistinclude and the HTML 5 custom data attribute (data-gistid) that contains the ID of the gist you’d like to include. Note that it doesn’t matter which element you use, but one that won’t have an impact on the layout of your page will work best (i.e. <span>, <em>, or <samp>). In my case, I used an ordinary <p> tag to avoid markdown automatically wrapping the code with a <p> tag.

And here’s the jQuery that grabs the specified gists and embeds them on the page. Nothing really fancy here, just remember that you have to use a callback (making it a JSONP call) in order to grab the data from a domain other than your own.

Another thing worth noting about doing it this way is the default gist embed stylesheet isn’t included by default. You may opt to include it during the AJAX call, or create your own styles to match the look and feel of your site.

This code is free to use without crediting me, and is released as-is without any warranty. If you have any questions or comments, please @reply me on Twitter.

Posted by @mclaughj Tagged with #jquery, #code, and #development.