Lazy loading Disqus with IntersectionObserver

Lazy loading Disqus with IntersectionObserver

   Leave a comment    http://bit.ly/2sls2hJ

We’re all keenly aware of how important performance is in this day and age of web development. Whilst recently looking over a site and checking it with PageSpeed, it showed that a big impact for mobile was the loading of the disqus commenting system. Changing Disqus to lazy-load increased the mobile PageSpeed score from mid 50’s to 95 (which is a massive change). With all of this change due to cutting down the number and size of many http requests being downloaded on page load (rather than when you need it).

There are many solutions out there to lazy load disqus, but this one uses the IntersectionObserver API, which makes it fast and efficient (no scroll events here). It does also have a fallback to load the comments anyway if the intersection observer api is not available.

HTML:

<div id="disqus_thread" data-shortname="{{ Your Disqus Shortname }}"></div>

JS:

if (document.getElementById("disqus_thread") !== null) {
    if ("IntersectionObserver" in window) {
        startDisqusObserver();
    } else {
        loadDisqus($("#disqus_thread").attr('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]});
    disqus_observer.observe(document.querySelector("#disqus_thread"));
}

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

Photo by J. Wynder

˜

Leave a Reply

Your email address will not be published. Required fields are marked *