How to load Disqus asynchronously

The default script from Disqus loads the comments when the page is first loaded. This adds more weight to the page size. For most blog page the disqus comments are not in the viewport, and can be loaded when the page is scrolled.

Syntax:

 var disqusDiv = document.getElementById('all-comments');
  if ( disqusDiv ){ 
    $(window).scroll(function(){
      // Remove the event, we just load once
      $(window).off('scroll');
    					
      //Load Disqus here 
    }
  }

Example:

Here a full example with the Disqus script. The variable disqus_shortname should hold your Disqus id.

 var disqusDiv = document.getElementById('all-comments');
  if ( disqusDiv ){ 
    $(window).scroll(function(){
	// Remove the event, we just load once
	$(window).off('scroll');
    					
    // DON'T EDIT BELOW THIS LINE
    (function () {
      var loaded = false;
      function loadDisqus() {
        if (loaded) return;
        loaded = true;
        var div = document.getElementById('all-comments');
        div.innerHTML = ''; div.id = 'disqus_thread';

        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);
      }

      if ( document.getElementById('all-comments') || document.readyState === "complete" ) {
        return setTimeout( loadDisqus, 1 );
      }

      if ( document.addEventListener ) {
        document.addEventListener( "DOMContentLoaded", loadDisqus, false );
        window.addEventListener( "load", loadDisqus, false );
      } else if ( document.attachEvent ) {
        document.attachEvent( "onreadystatechange", loadDisqus );
        window.attachEvent( "onload", loadDisqus);
      }
    }());    					
  }); 
}

References:

jQuery

Disqus

Recent Comments