Loading Disqus Comments On Demand Without jQuery or AJAX

Posted in General

There are many posts around the internet about loading Disqus comments on demand, however, I found many of them either rely on jQuery, try and load the embed.js file via ajax and run into CORS issues or just lack small bits of functionality. So I thought I would put everything together in one gist.

If you are reading this then the chances are that I don't need to explain why anyone would want to prevent comments loading by default, so I will move directly on to the code.

To use, add the code where you want the comments to display and change the disqus_shortname from xxxx to your actual username.

For a long explanation of how it works, you can find the original post by Amit Agarwal here. The post also contains a snippet to get comments to load as the user scrolls to the bottom of the page.

The small changes I made:

  • Remove the disqus_identifier, since the page url is picked up automatically anyway.
  • Separated the load button from the thread and remove the button on click so it can be placed away from the comments area.
  • Added a check for urls that contain a hash starting with 'comment-' to load the comments when linked to directly (Either from a  Disqus email or a link within the page content).
  • Added a check to load comments automatically for search engines.

Loading comments for search engines could be viewed as a good or bad thing. It will slow the page loading time, but allow the comments to be read (For search engines that can read javascript content such as Google). Search engines that can read JavaScript can probably also work out what happens when they click on the button, but I thought I would give it a go anyway to see what happens.

If you test the automatic loading for search engines by changing your useragent, you will notice that the comments lack some styling. This is normal and intentional as Disqus will load a simple iframe showing basic comments that search engines can read.

How Disqus comments are seen by search engines