Loading Disqus On Demand

Loading Disqus On Demand

Disqus is a great comment system that is all too easy to implement. Simply grab and paste the provided snippet (or install the plugin) and presto! Users are good to go discussing and sharing away. This is all good and well if you're fine with the vanilla functionality that automatically displays the discussions, but what to do if you want to reduce page clutter and let users load comments on demand?

First, we'll probably need a button that will load the comments when the user activates it. Place the following snippet where you'd like the button and comments to appear.

You could also just place a <div> element with the id #comments-access, or the id of your choosing (see JavaScript explanation to follow). However, our functionality requires JavaScript, so we're actually creating our button with JavaScript. This is done in the case that a user doesn't have JavaScript enabled, a seemingly useless button won't be displayed.

Next, make sure you've included jQuery and place the following JavaScript just before the end of your </body> tag.

var disqus_shortname = 'example'; // required: replace example with your forum shortname

// Below may be omitted
$(document).ready(function($){
  $("#comments-catalyst").append("Access Comments");
});

// No need to edit below
function loadComments(catalysts, links) {
  $(document).ready(function($){
    if(typeof disqus_shortname !== "undefined") {
      if(!catalysts) {
        catalysts = "#comments-access";
      }
      catalyst_elements = $(catalysts);
      catalyst_link_elements = catalyst_elements.add(links);
      catalyst_link_elements.click(function() {
        $.ajaxSetup({
          cache: true
        });
        $.getScript("http:\/\/" + disqus_shortname + ".disqus.com\/embed.js");
        $.ajaxSetup({
          cache: false
        });
        catalyst_elements.remove();
      });
    }
  });
}

/*
Function accepts 2 arguments e.g.:
loadComments("#my-custom-id", ".link-element-1, .link-element-2");
*/
loadComments();

Some configurations are required. First, at var disqus\_shortname, be sure to replace example with your forum shortname. The section of code marked Below may be omitted, is aforementioned functionality that creates our button. If you're manually creating your button you may omit this code. Finally, notice the call to the function loadComments. It accepts 2 arguments. The first is optional and needs to be specified if you manually placed a <div> element with an id of your choosing other than the id #comments-access. The second argument is optional and is for link elements elsewhere that would load Disqus but wouldn't be removed like the button element.

As you might have noticed, the trick is jQuery's handy .getScript() method. It really is what makes solving the problem of allowing users to load Disqus on demand possible. This page is one example of an implementation. Another example can be found here.