Load Disqus Comments on demand/click

The comments on this site are powered by Disqus, which is a popular commenting platform offering more features than what the native commenting solutions of Drupal or WordPress have in store.

By default, Disqus widget is loaded asynchronously meaning it will download the JavaScript in parallel. Even though this is supposed to minimally affect page speed, it still affects the load time of your web pages as weight of your pages will increase even if end-user isn't interested in participating in discussion.

Solution: load Disqus scripts on-demand with JavaScript.

Advantages

  • Faster page load overall
  • Better Core Web Vitals score
  • Decreased page length, easier to scroll up and down
  • Less spam comments

Disadvantages

  • Extra click for commenting might lead to less contribution in comments

 

Bellow is an example of how above can be achieved with Alpine.Js

<button
  x-data="disqusComponent()"
  x-show="!loaded"
  @click="toggle()"
>Show/Post Comments
</button>

<div id="disqus_thread"></div>

<script>
  var disqus_config = function () {
    this.page.identifier = "my/unique/id";
    this.page.url = "https://cornel.co/article/load-disqus-comments-demand";
  };

  function disqusComponent() {
    return {
      loaded: false,
      toggle() {
        if (!this.loaded) {
          var e = document.createElement("script");
          e.type = "text/javascript";
          e.async = true;
          e.src = "//" + "my-disqus-shortname" + ".disqus.com/embed.js";
          (document.getElementsByTagName("head")[0] ||
            document.getElementsByTagName("body")[0])
            .appendChild(e);
          this.loaded = true;
        }
      }
    }
  }
</script>

 

Additionally, if you're worried that comments won't be crawled by search engines, add the following snipped to toggle comments on page request.

if(/bot|google|baidu|bing|msn|duckduckgo|slurp|yandex/i.test(navigator.userAgent)) {
   // Trigger Disqus scripts...
}

 

********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************