Disqus: Detect when comment count has loaded

With Django deprecating their contrib comments module, they suggested that we switched to Disqus as an alternative. It's pretty good, but I found that it was a little tricky to configure stuff on the Javascript side of things.

Sometimes we get a nice callback option to know when values have been filled in. That way we can tweak the output to suit our site if needed.

Not in the case with Disqus' count.js script. It populates any elements with a URL ending with "#disqus-thread" or the attribute "data-disqus-identifier" with the count values fetched from the Disqus server.

The only problem is we don't know when that's done, and it also fills in "0 comments" for us when we may not want it to.

The tl;dr solution

Here's the default unmodified script they tell you to paste in:

<script type="text/javascript">
var disqus_shortname = 'YOUR_SITENAME';
(function () { var s = document.createElement('script');
s.async = true;
s.type = 'text/javascript';
s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);

And this is what I'm telling you to paste in:


If you haven't noticed already, the modified version uses jQuery in two places. If you don't want to use jQuery, then you should be able to port this code to any other Javascript library fairly easily.

The first place is via $.getScript(). This loads the count.js script file, executes it and then calls the callback function disqus_counts_loaded().

When the script is done with whatever it needs to do, it inserts another script called count-data.js into your page to fetch the data.

When count-data.js is loaded, DISQUSWIDGETS.displayCount() is automatically called to fill the elements full of the new luscious data.

Because we overridden displayCount() with our own function, it now fires an event afterwards to any elements wishing to know when the "disqus-counts-loaded" occurs.

Example usage

<script type="text/javascript">
$('.comments').bind('disqus-counts-loaded', function() {
var obj = $(this);

if (obj.text() == "0 Comments") {
else if (obj.hasClass("user-review")) {
obj.text(obj.text().replace("Comments", "User reviews"));

This snippet hides anything that says "0 Comments". Why? Because it's distracting. It also changes "Comments" with "User reviews" on certain elements.

Spot the difference between the before/after screenshots.


The layout on the right is much cleaner with  the "0 comments" clutter hidden away.


Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog