How to load Disqus comment box only when the page is scrolled?

Updated on September 2, 2017

If you are using Disqus comment box on your website and wish to load it only when the user scroll down the page, then you have landed on the right page. Sometimes Disqus takes time to load and that can considerably increase the load time of your website. While I was wondering how to do this, my friend Santhosh suggested this trick and thankfully it worked like a gem. The idea here is to load the Disqus comment box only when the user really needs it. For instance, if any visitor wants to comment on a particular article, then he/she has to scroll down the page and that’s the time we are going to load Disqus.

Loading Disqus comment box via Ajax when user scrolls down the page

Disqus comment box loading
Disqus comment box loadingD

Step 1: Copy and paste the below code in footer (footer.php or whatever)

jQuery(document).ready(function ($){
var disqus_div = $("#disqus_thread");
if (disqus_div.size() > 0 ) {
var ds_loaded = false,
top = disqus_div.offset().top,
disqus_data = disqus_div.data(),
check = function(){
if ( !ds_loaded && $(window).scrollTop() + $(window).height() > top ) {
ds_loaded = true;
for (var key in disqus_data) {
if (key.substr(0,6) == 'disqus') {
window['disqus_' + key.replace('disqus','').toLowerCase()] = disqus_data[key];
}
}
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = 'http://' + window.disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}
};
$(window).scroll(check);
check();
}
});

Step 2: If you are using WordPress, then copy and paste the below code in single.php

<div id="disqus_thread" data-disqus-shortname="your_disqus_username" data-disqus-url="<?php the_permalink(); ?>"></div>

Note: Replace your_disqus_shortname with your disqus-shortname.

Step 3: If you are using Blogger, then copy and paste the below code in your Blogger template

<div id="disqus_thread" data-disqus-shortname="your_disqus_username" expr:data-disqus-url='data:post.url'></div>

Note: Replace your_disqus_shortname with your disqus-shortname.

That’s it! Save it and hit Ctrl-F5 to reload the page. Now the Disqus comment box should load only when the user scrolls the page.

Thanks to TechAbly.

Was this article helpful?

Related Articles

Comments Leave a Comment

Leave a Comment