My new jQuery plugin: load gists dynamically in a Backbone application

I occasionally use GitHub gists to display blocks of code in some blog posts. Recently, I found out that the normal way of embedding a gists in a page doesn’t work for HTML5 applications like this blog’s small Backbone client application. The official way to load a gist is via a <script> tag:

<script src="https://gist.github.com/mstapp/9452045.js?file=1.js"></script>

This works for the very first page load, which is rendered on the server, but those scripts don’t work for pages that are rendered dynamically. (The reason is a bit of a rat-hole, but it’s because those scripts load asynchronously and then try to modify the document via document.write calls. The browser doesn’t know where in the document to make those write changes, and it can’t sequence multiple <script> tags in the new content because they’re asynchronous and don’t return in a defined order.)

I found a few different ways to handle this, and put together bits & pieces of different solutions to come up with something that is both simple & works well. I made a small jQuery plugin named jquery.ajax-gist (GitHub) so I could use the code in different applications.

In my page content, I embed a gist by adding a <div> element instead of a <script> tag, and include the gist’s URL in a data-gist attribute:

<div data-gist="https://gist.github.com/9577835.js?file=1.js"></div>

Then in my blog’s Marionette views, I call the plugin to load the gists for all of those similar div elements in the view’s newly-rendered content:

// In my Marionette view class:

onRender: function() {
    this.$('div[data-gist]').ajaxgist();
}

That creates a set of all <div> elements with a data-gist attribute, and passes that whole set to the plugin’s ajaxgist() function.

Inside the ajaxgist(), the plugin makes ajax calls to get the gists in a JSON document (which is very handy – thanks, GitHub!). After that, it’s an easy step to just replace those original div elements with the gist markup from the JSON documents. From the plugin:

// replace script with gist html
$el.replaceWith( $(data.div) );

The plugin also makes sure that the gist CSS stylesheet gets added to the document once (the gists’ JSON also includes the URL of the stylesheet), and the end result is that I can load gists in my dynamically-loaded blog pages.

I like the result: it was a quick way to solve the problem, the solution turned out to be a pretty good one, and it was nice to hide the more complex part behind the simple interface of a jQuery plugin.