Skip to content

Instantly share code, notes, and snippets.

@prinsss
Created June 25, 2017 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prinsss/2e0e0c127a0f5081434b4dbe136327c1 to your computer and use it in GitHub Desktop.
Save prinsss/2e0e0c127a0f5081434b4dbe136327c1 to your computer and use it in GitHub Desktop.
Hexo 访问计数器,前端示例脚本。
/**
* 这里处理一下 slug,去掉多余字符。
* Hexo 博客中的页面(即 layout 为 page)的 `page.path` 会带上一个 `index.html`,搞不懂为什么。
*/
String.prototype.cleanSlug = function () {
var search = '/index.html';
if (this.indexOf(search) === -1) {
return this.slice(0, -1)
} else {
return this.replace(search, '');
}
}
var Counter = function (url) {
this.baseCounterUrl = url;
this.initAllPostViews = function () {
var self = this;
// 遍历 post-view
// 如果你的容器不是这个 ID,请自行修改
$('[id=post-view]').each(function () {
// 默认 PV 设为 0
var span = $(this).html(0);
// 获取文章 slug,按需修改,我是把文章的 `post.path` 直接写入计数器容器的 `data` 属性了
var slug = span.attr('data').cleanSlug();
self.getPostViewBySlug(slug, function (pv) {
span.html(pv);
})
});
}
this.getPostViewBySlug = function (slug, callback) {
var url = this.baseCounterUrl + '/get/' + slug;
$.getJSON(url, function (data) {
callback(data.pv);
});
}
this.incPostViewBySlug = function (slug) {
var url = this.baseCounterUrl + '/increase/' + slug;
$.post(url, {}, function (data) {
$('#post-view').html(data.pv);
});
}
}
// 参数中的 URL 修改为你自己的部署地址
var counter = new Counter('https://work.prinzeugen.net/hexo-view-counter');
{# 给你每篇文章页脚都加上这个,用于显示访问量的容器 #}
{# 这里用的 Swig 模板,其他模板引擎大同小异 #}
<span class="pmt pms fa-eye">
<span id="post-view" data="{{ post.path }}">Loading</span> Hits
</span>
{# 初始化页面上所有的计数器 #}
<script type="text/javascript">
$(document).ready(function () {
counter.initAllPostViews();
});
</script>
{# 当前为 Post 页或者 Page 时给访问量 +1 #}
{% if (is_post() || page.layout == 'page') %}
<script type="text/javascript">
counter.incPostViewBySlug(
$('#post-view').attr('data').cleanSlug()
);
</script>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment