Load Disqus on Demand with JavaScript


As an alternative, you can configure Disqus on your website to load on-demand and not automatically. When someone clicks a button – like the example here – the widget will be dynamically added to your web page and not otherwise. This lazy-loading technique can be implemented in pure JavaScript without jQuery.
Step 1: Go to your web page template that has Disqus and replace the #disqus_thread <div> with the following snippet:
  1. <div id="disqus_thread">
  2. <a href="#" onclick="disqus();return false;">Show Comments</a>
  3. </div>
Step 2: Next place the Disqus code before the close <head> tag of your web page. You’ll have to replace the disqus variables – like disqus_shortname, disqus_url, etc. – with your own parameters.
  1. <script type="text/javascript">
  2.  
  3. // Replace labnol with your disqus shortname
  4. var disqus_shortname = "labnol";
  5.  
  6. // Put the permalink of your web page / blog post
  7. var disqus_url = "http://example.com/blog-post";
  8.  
  9. // Put the permalink of your web page / blog post
  10. var disqus_identifier = "http://example.com/blog-post";
  11.  
  12. var disqus_loaded = false;
  13.  
  14. // This is the function that will load Disqus comments on demand
  15. function disqus() {
  16.  
  17. if (!disqus_loaded) {
  18. // This is to ensure that Disqus widget is loaded only once
  19. disqus_loaded = true;
  20. var e = document.createElement("script");
  21. e.type = "text/javascript";
  22. e.async = true;
  23. e.src = "//" + disqus_shortname + ".disqus.com/embed.js";
  24. (document.getElementsByTagName("head")[0] ||
  25. document.getElementsByTagName("body")[0])
  26. .appendChild(e);
  27. }
  28. }
  29.  
  30. </script>
The page will have a “Show Comments” button and the comments are only loaded when the button is clicked.
Some websites have auto-loading enabled for Disqus but the widget is loaded when the reader has scrolled to the bottom of the  article. This can again be done in JavaScript. We can use the onscroll method to check whenever the page is scrolled and if the user is near the bottom, the script will load the Disqus widget.
Place this snippet near the closing </body> tag of your page.
  1. <script type="text/javascript">
  2. window.onscroll = function(e) {
  3. if ((window.innerHeight + window.scrollY)
  4. >= document.body.offsetHeight)
  5. {
  6. if (!disqus_loaded) disqus();
  7. }
  8. };
  9. </script>
Home — How-to Guides — Code — JavaScript