Enabling Disqus comments on a custom Tumblr theme using jQuery

The official “Universal Code” that is suggested by Disqus for embedding the comment widget injects a new <script> element into the page and looks a bit messy. The embedding can be achieved with cleaner code using jQuery’s JSONP support.

Here’s the code suggested by Disqus:

(function() {
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = 'http://magnetiq.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0]
        || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();

I was a bit thrown off by the amount of code that I would have to include in my custom template to dynamically embed the Disqus script. Already using jQuery for some progressive enhancement, I realized that I could use the following succinct implementation as an alternative:

$.ajax({
    url: "http://magnetiq.disqus.com/embed.js",
    dataType: "jsonp"
});

And here’s the full Tumblr theme excerpt:

...
<meta name="text:Disqus Shortname" content=""/>
...
</head>
<body>
...
{block:PermalinkPage}
{block:IfDisqusShortname}
<div class="section" id="disqus_thread"></div>
<div class="section" id="dsq-loading-problem"></div>
<script type="text/javascript">
$.ajax({
    url: "http://{text:Disqus Shortname}.disqus.com/embed.js",
    dataType: "jsonp"
});
</script>
{/block:IfDisqusShortname}
{/block:PermalinkPage}
...

While this seems to work for now, I had to include the dummy dsq-loading-problem div to prevent a JavaScript runtime error. I will do more digging later to see what’s going on…

Update

Using the getScript function makes it a lot better:

$.getScript("http://magnetiq.disqus.com/embed.js");