How to lazy load Disqus using vanilla/native javascript!

I recently found out that my blog was slow according to google pagespeed. I scored below 50, but I could have sworn that when I created my blog it was in the 90s. There were two reasons for this, Google Adsense and Disqus. Both took an immense amount of resources to load and had extra scripts and resources that they needed, this slowed down the initial load of my pages. Therefore I decided to lazy load disqus so my pages would load faster.


For my blog i use Ghost pro which is a blogging platform. In my HTML I have the standard disqus setup with a div that has a "disqus_thread" id:

<div id="disqus_thread" post-id="{{comment_id}}" post-url="{{url absolute="true"}}">	

In the above HTML there are two attributes, the post-id and the post-url. The post-id is the unique id of the page and the post-url is the canonical URL of your page. These you likely already have and are good to go and you do not need to change what you already have in your HTML, now you just want to lazy load Disqus.

In order to lazy load Disqus I made a small javascript script:

var element = document.getElementById('disqus_thread');
if (element === null)

var isLoaded = false;

window.addEventListener('scroll', function (e) {
	var currentScroll = document.scrollingElement.scrollTop;

	if (!isLoaded && (currentScroll > element.getBoundingClientRect().top - 100)) {
		isLoaded = true;

        //TODO Insert your usual disqus code after this line, mine is below:
        window.disqus_config = function () {
   = element.getAttribute('post-url');
   = element.getAttribute('post-id');
        var d = document, s = d.createElement('script');

        s.src = '//';

        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
}, false);

In the above I first check if the disqusthread div is present, if not I do nothing because not all my pages have Disqus. If it is present I add an event listener to the scroll of the page. When the user scrolls I check if they are a 100 pixels from the Disqus thread div and if so I initialize it. In the above TODO part you need to place your own code!, at least for the src attribute. This will make Disqus load only when your users scroll and if your users are about to see the Disqus comments.

I think this is a very simple solution. I hope you liked it! please let me know in the comments down below - of course powered by lazy loaded Disqus :)