wordpress文章浏览历史(非插件版)

2020-08-30 11:29:41

wordpress如果添加文章浏览记录区域,可以很好的提高网站的用户体验 比如: 某人经常通过搜索引擎进来我的网站, 可能发现以前在这里也看过一些文章, 比较合他口味, 久而久之就能发展成常客.
如果懒得看可以直接使用插件:wordpress文章浏览历史插件

【实现原理】

这个功能实现非常简单, 平白一点来说就是找个地方将页面一些信息保存起来, 如果页面两次被访问, 新的内容覆盖掉旧的内容; 在页面加载的时候, 将保存的信息取出显示.

实现方法也很多, 最土的是将内容保存在 cookie 中, 但用 cookie 储存数据存在一些问题. 比如: cookie 是随 HTTP 响应一起被发送的, 会对服务器端响应时间产生一定程度的影响, 尤其是在使用 XMLHttpRequest 对象向服务器端发送或请求数据的时候.

利用 cookie 虽然比较土, 但最实用, 因为几乎可以兼容所有浏览器. 我这里使用的 localStorage, 数据完全保存在浏览器中, 不会有影响服务器响应, 但 IE6/7 中不能使用.

这里要完成以下几个功能点:

将存储内容转成数组对象, 因为 localStorage 只能保存字符串.
去重, 如果保存的内容已经存在, 则删除旧数据, 以最新的为准.
限制保存数量, 没有必要无限保存历史导致列表超长.

【实现步骤】

我已经写好了一个名为 View History 的脚本, 不到 50 行代码, 就是为了实现上述的三个功能.
1. 引用脚本并初始化对象

/* */

2. 在文章页面保存浏览信息

/* */

3. 显示历史浏览记录

/* 0) {
for(var i=histories.length-1; i>=0; i--) {
var history = histories[i];

var item = document.createElement('li');
var link = document.createElement('a');
link.href = history.url;
link.innerHTML = history.title;

item.appendChild(link);
list.appendChild(item);
}

// 插入页面特定位置
wrap.appendChild(list);
}
}
/* ]]> */


【说明】

只用 localStorage 做历史浏览记录不能解决时效性问题, 也就是不能获得最新的文章信息. 如果我将文章评论数加到浏览记录中, 那么用户看到的仅是他访问当时的评论数量. 解决办法是有的, 有些网站只保存文章的 ID, 在页面加载时再动态加载文章信息, 比如: 评论数和平均评价.

附完整代码:


ViewHistory = function() {

this.config = {
limit: 10,
storageKey: 'viewHistory',
primaryKey: 'url'
};

this.cache = {
localStorage: null,
userData: null,
attr: null
};
};

ViewHistory.prototype = {

init: function(config) {
this.config = config || this.config;
var _self = this;

// define localStorage
if (!window.localStorage && (this.cache.userData = document.body) && this.cache.userData.addBehavior && this.cache.userData.addBehavior('#default#userdata')) {
this.cache.userData.load((this.cache.attr = 'localStorage'));

this.cache.localStorage = {
'getItem': function(key) {
return _self.cache.userData.getAttribute(key);
},
'setItem': function(key, value) {
_self.cache.userData.setAttribute(key, value);
_self.cache.userData.save(_self.cache.attr);
}
};

} else {
this.cache.localStorage = window.localStorage;
}
},

addHistory: function(item) {
var items = this.getHistories();
for(var i=0, len=items.length; i 0 && items.length > this.config.limit) {
items.splice(0, 1);
}

var json = JSON.stringify(items);
this.cache.localStorage.setItem(this.config.storageKey, json);
},

getHistories: function() {
var history = this.cache.localStorage.getItem(this.config.storageKey);
if(history) {
return JSON.parse(history);
}
return [];
}
};