Dynamic Gists Using MutationObservers and Promises

Published on by Morgan Ney

If you load your blog posts dynamically, after the window's onload event has fired, then using GitHubs provided embed <script> for your Gists, which relies on document.write(), is not going to work. Embedding Gists into XHR loaded content will take a bit more work. I decided to write a Backbone.View using MutationObservers and Promises that would embed Gists after dynamically loading my blog content.

To keep my view logic simple, I needed to write a module to encapsulate the mechanics of actually fetching the Gists from GitHub (using JSONP) and updating the DOM with the Gist in the right location. Here is a jQuery based approach to writing a Promise-returning function to fetch your Gists:

The only other major hurdle is updating the DOM with the Gist once its fetched. Since I'm relying on MutationObservers to know when my dynamic content has been added to the page, the MutationObserver callback is where I'll handle inserting the Gist after fetching it with the function above. Here is another jQuery based approach:

At this point the interface (API) of our "Gister" module looks something like this (assuming a RequireJS implementation):

Now I can actually write the Backbone.View that will utilize the Gister module. This will be a "PostView" view which listens for changes to a "Post" model before rendering. The render method of PostView is what triggers it's internal MutationObserver to use Gister for embedding the Gist, while the Post model will fetch the dynamic content (a blog post in this case). Again, I'll wrap my PostView as a RequireJS module:

With all the pieces in place I can actually use my PostView to embed Gists dynamically. The application logic might look as simple as:

MutationObservers and Promises are two of the more useful API's out there, unfortunately only Chrome 32+ supports them both. Luckily you can find poly fills. A more useful version of Gister is hosted on GitHub, and it can be loaded as an AMD module or traditional <script> tag. Needless to say, it only works with modern browsers or polyfill support.

Relevant to  MutationObserver, Promise, Backbone, jQuery
Get in Touch

BizzyBtyes is owned by Morgan Ney, a father, husband, and web developer originally from the San Francisco Bay Area and now living in Coarsegold, Ca. just south of Yosemite.