If you’re working in the direction to make your website fast-loading, you should also think on loading the comment section of your site on user demand asynchronously; i.e. through AJAX.

In simple words, the comment section won’t be loaded when a page or post of your site will be requested. Therefore, you’re site will be loaded little bit faster than it would load with all the comments, comment form etc. Now, the comment section will only be loaded when the user clicks certain button or link. I guess that sounds savvy enough.

Loading Disqus comments through AJAX ‘onclick’

Platform independent commenting systems like Disqus are quite popular these days, as they offer a lot of features and added functionalities to make comments; so if you’re using Disqus on your site to allow users to comment, we’re going to take a look how to load Disqus comments on click event through AJAX.

jQuery to load Disqus ‘onclick’

Add this code to your site where you want to make Disqus comments to appear only when a button is clicked. Prerequisite: Your site must be using jQuery.

<div id="disqus_thread"></div>
<div id="disqus_loader">
<button onclick='
  jQuery.ajaxSetup({cache:true});
  jQuery.getScript("http://YOUR_DISQUS_USERNAME.disqus.com/embed.js");
  jQuery.ajaxSetup({cache:false});
  jQuery("#disqus_loader").remove();
'>
Post a Comment
</button>
</div>

Non-jQuery, plain JS version

In case you are not using jQuery on your website for some reason (site speed basically), you may want this code snippet in plain JavaScript format. You need not to bother much, use the below given JavaScript on your site:

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

With the above script, we defined the load_disqus() function to load Disqus comments when used. Use this function with a markup element on the click event; for eg.:

<button onclick="load_disqus();">Load Comments</button>
<div id="disqus_thread"></div>

Hope you found it useful. Don’t forget to replace the red highlighted YOUR_DISQUS_USERNAME field to your Disqus username in the above codes.

Notes

  • The div with id disqus_thread will be the place where the comments will be loaded on using any of the above two ways.
  • Your Disqus username is the name you use to log into your Disqus account.
  • Don’t go for the jQuery method if you’re not using it on your website – using it just to load comments is not a good idea.