6

点击再载入 Disqus 的评论模块

 2 years ago
source link: https://www.codewoody.com/posts/5560/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Published Jun 16, 2021

点击再载入 Disqus 的评论模块

本博客采用了 Disqus 的评论系统,然而遗憾评论数非常少,所以每次都直接载入评论模块感觉会浪费带宽和流量。所以我希望实现 Lazy Load 方式载入评论,即只要用户点击一个按钮之后才会显示评论模块。

eb97bbed7fe891372322d0ca8187b59a.gif

下面是不依赖任何库的 JavaScript 实现版本:

<script>
function load_disqus( disqus_shortname ) {
// Prepare the trigger and target
var disqus_trigger = document.getElementById('disqus_trigger'),
disqus_target = document.getElementById('disqus_thread'),
disqus_embed = document.createElement('script'),
disqus_hook = (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]);

// Load script asynchronously only when the trigger and target exist
if( disqus_target && disqus_trigger ) {
disqus_embed.type = 'text/javascript';
disqus_embed.async = true;
disqus_embed.src = '//' + disqus_shortname + '.disqus.com/embed.js';
disqus_hook.appendChild(disqus_embed);
disqus_trigger.remove();
console.log('Disqus loaded.');
}
}
</script>
<div id="disqus_thread"></div>
<button id="disqus_trigger" onclick="load_disqus('your_disqus_shortname')">Post a Comment</button>
</div>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

注意替换 buttononclick 调用函数参数 your_disqus_shortname 的内容。

参考链接


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK