99+ Google Pagespeed Score with Disqus

If you’re into your front-end web performance you will probably have heard of Google Pagespeed and/or Lighthouse as tools to test and measure how quickly and efficiently you web pages load. This is also something we use here on this site to make your reading as pleasant as possible.

But, we also use the online commenting system called Disqus and the two don’t always play nicely together - in that Disqus loads lots of files and takes a while to load.

This is more of a JavaScript related issue than Hugo however, but an issue we come across a lot on Hugo-built sites.

pagespeed example

Our Solution

We load the commenting system only when someone scrolls to it. We use a thing called the IntersectionObserver api in JavaScript to watch for the scrolling, which calls loadDisqus() when we reach a threshold (600px away from it in this example).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// =============================
// Disqus
// =============================

var disqusEl = document.getElementById("disqus_thread");
if (disqusEl !== null) {
  if ("IntersectionObserver" in window) {
    startDisqusObserver();
  } else {
    loadDisqus(disqusEl.getAttribute('data-shortname'));
  }
}

// Look for when the user hits the comments before loading
function startDisqusObserver() {
  var disqus_observer = new IntersectionObserver(function(entries) {
    if (entries[0].isIntersecting) {
      loadDisqus(entries[0].target.getAttribute('data-shortname'));
      disqus_observer.disconnect();
    }
  }, {threshold: [0], rootMargin: "0px 0px 600px 0px"});
  disqus_observer.observe(document.querySelector("#disqus_thread"));
}

// Load the script
function loadDisqus(disqusShortname) {
  var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
  dsq.src = '//' + disqusShortname + '.disqus.com/embed.js';
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}

Put this where you need your comments to show:

1
2
<!-- JS lazy-loaded -->
<div id="disqus_thread" data-shortname="{{ .Site.DisqusShortname }}"></div>

You can test this out by opening your Dev Tools to the Network tab and monitoring the request that are sent by your browser.