懒加载 disqus 评论框

环境:hexo with theme NexT v6.0.0

默认情况下 disqus 评论框会在页面载入时立即加载,而由于国内无法访问 disqus.com,页面会较长时间停留在载入状态,体验贼鸡儿差……

设想

预计达到的效果是文章载入后,用户滚动页面到最底部时再开始载入评论框。

实现

打开 hexo/themes/next/layout/_third-party/comments/disqus.swig 文件,修改为以下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
{% if not (theme.duoshuo and theme.duoshuo.shortname) and not theme.duoshuo_shortname %}
{% if theme.disqus.enable %}

{% if theme.disqus.count %}
<script id="dsq-count-scr" src="https://{{theme.disqus.shortname}}.disqus.com/count.js" async></script>
{% endif %}

{% if page.comments %}
<script type="text/javascript">
var disqus_config = function () {
this.page.url = '{{ page.permalink }}';
this.page.identifier = '{{ page.path }}';
this.page.title = '{{ page.title| addslashes }}';
};
function loadDisqus() {
var d = document, s = d.createElement('script');
s.src = 'https://{{theme.disqus.shortname}}.disqus.com/embed.js';
s.setAttribute('data-timestamp', '' + +new Date());
(d.head || d.body).appendChild(s);
}
$(function () {
var offsetTop = $('#comments').offset().top - $(window).height();
if (offsetTop <= 0) {
loadDisqus();
} else {
$(window).on('scroll.disqus_scroll', function () {
var scrollTop = document.documentElement.scrollTop;
if (scrollTop >= offsetTop) {
$(window).off('.disqus_scroll');
loadDisqus();
}
});
}
});
</script>
{% endif %}

{% endif %}
{% endif %}

修改 disqus 评论个数

似乎只修改评论框还不够,文章标题下面的评论计数也是一个严重的阻塞对象。

打开 hexo/themes/next/layout/_third-party/comments/disqus.swig 文件,修改以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
--- a/hexo/themes/next/layout/_third-party/comments/disqus.swig
+++ b/hexo/themes/next/layout/_third-party/comments/disqus.swig
@@ -2,7 +2,25 @@
{% if theme.disqus.enable %}

{% if theme.disqus.count %}
- <script id="dsq-count-scr" src="https://{{theme.disqus.shortname}}.disqus.com/count.js" async></script>
+ <script type="text/javascript">
+ $(function() {
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', '//disqus.com/next/config.json', true);
+ xhr.timeout = 2500;
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4 && xhr.status === 200) {
+ $('.post-meta .post-comments-count').show();
+ var s = document.createElement('script');
+ s.id = 'dsq-count-scr';
+ s.src = 'https://{{theme.disqus.shortname}}.disqus.com/count.js';
+ s.async = true;
+ (document.head || document.body).appendChild(s);
+ }
+ };
+ xhr.ontimeout = function () { xhr.abort(); };
+ xhr.send(null);
+ });
+ </script>
{% endif %}

{% if page.comments %}

这里首先验证当前环境能否获取到 //disqus.com/next/config.json 文件(2.5s 超时),如果获取成功,则加载 {{theme.disqus.shortname}}.disqus.com/count.js 脚本[1]

参考:[1] 检测网络是否能够访问 Disqus - http://blog.fooleap.org/check-network-able-to-access-disqus.html