Skip to content

Commit 72273b6

Browse files
KaitoHH1v9
authored andcommitted
Improve page rendering by deferring disqus loading (#891)
1 parent ff4ddde commit 72273b6

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

layout/_third-party/comments/disqus.swig

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
{% if theme.disqus.count %}
2-
<script id="dsq-count-scr" src="https://{{ theme.disqus.shortname }}.disqus.com/count.js" async></script>
2+
<script>
3+
function loadCount() {
4+
var d = document, s = d.createElement('script');
5+
s.src = 'https://{{ theme.disqus.shortname }}.disqus.com/count.js';
6+
s.id = 'dsq-count-scr';
7+
(d.head || d.body).appendChild(s);
8+
}
9+
// defer loading until the whole page loading is completed
10+
window.addEventListener('load', loadCount, false);
11+
</script>
312
{% endif %}
413
{% if page.comments %}
514
<script>
@@ -22,7 +31,7 @@
2231
var offsetTop = $('#comments').offset().top - $(window).height();
2332
if (offsetTop <= 0) {
2433
// load directly when there's no a scrollbar
25-
loadComments();
34+
window.addEventListener('load', loadComments, false);
2635
} else {
2736
$(window).on('scroll.disqus_scroll', function() {
2837
// offsetTop may changes because of manually resizing browser window or lazy loading images.
@@ -38,7 +47,7 @@
3847
}
3948
});
4049
{% else %}
41-
loadComments();
50+
window.addEventListener('load', loadComments, false);
4251
{% endif %}
4352
</script>
4453
{% endif %}

layout/_third-party/comments/disqusjs.swig

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,25 @@
88
{% if theme.vendors.disqusjs_js %}
99
{% set disqusjs_js_url = theme.vendors.disqusjs_js %}
1010
{% endif %}
11-
<script src="{{ disqusjs_js_url }}"></script>
1211

1312
<script>
14-
var dsqjs = new DisqusJS({
15-
api: '{{ theme.disqusjs.api }}' || 'https://disqus.com/api/',
16-
apikey: '{{ theme.disqusjs.apikey }}',
17-
shortname: '{{ theme.disqusjs.shortname }}'
18-
});
13+
function initialDsq() {
14+
window.dsqjs = new DisqusJS({
15+
api: '{{ theme.disqusjs.api }}' || 'https://disqus.com/api/',
16+
apikey: '{{ theme.disqusjs.apikey }}',
17+
shortname: '{{ theme.disqusjs.shortname }}',
18+
url: {{ page.permalink | json }},
19+
identifier: {{ page.path | json }},
20+
title: '{{ page.title | addslashes }}',
21+
});
22+
}
23+
24+
function loadDsqJS() {
25+
var d = document, s = d.createElement('script');
26+
s.src = '{{ disqusjs_js_url }}';
27+
s.onload = initialDsq;
28+
(d.head || d.body).appendChild(s);
29+
}
30+
31+
window.addEventListener('load', loadDsqJS, false);
1932
</script>

0 commit comments

Comments
 (0)