按照 Disqus 的文档把提供的代码添加到 ghost 的主题文件,然后进行一些修改,让 Disqus 能够延迟加载,以前是用的点击按钮加载 Disqus 的方式,现在改成了在滚动到某个位置时加载 Disqus。
把原有 Disqus 相关的代码改成这样,定义函数而不执行它。
<script type="text/javascript">
var disqus = {
load : function disqus() {
/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'xxxxxxxxxx';
if (typeof DISQUS !== 'object') {
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
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);
})();
}
}
}
</script>
在这段代码之后找个合适的位置添加下面的关键代码
<script type="text/javascript">
(function (){
var content = document.querySelector('.post-content');
var extra_height = (content.getBoundingClientRect().top + window.scrollY + content.clientHeight) / 4;
var footer_top = document.querySelector('.post-footer').getBoundingClientRect().top + window.scrollY;
var load_pos = footer_top - extra_height;
document.addEventListener('scroll', function _func() {
if (load_pos - window.scrollY <= window.screen.availHeight) {
disqus.load();
document.removeEventListener('scroll', _func);
}
});
})();
</script>
定义了一个匿名函数,立即执行它。前面几行代码计算了一个比较合适的位置,然后给这个匿名函数内,给滚动事件绑定了一个 _func
函数,在这个 _func
函数内,当滚动到计算的位置时,调用 Disqus 的加载函数,随后在函数内就解绑,即把函数名 _func
作为 removeEventListener
的第二个函数。