hexo-cache
用于hexo博客添加service worker缓存支持
- 安装
npm install hexo-cache --save
- 给HTML模板添加一段JavaScript,以next主题为例
layout文件夹 -> _layout.swig文件
在
header
标签上方上添加如下代码
<style>
.x-msg {
position: fixed;
left: 0;
right: 0;
top: 0;
height: 50px;
line-height: 50px;
text-indent: 20px;
color: #fff;
font-size: 16px;
background: #91d5ff;
}
.x-close {
position: absolute;
right: 10px;
cursor: pointer;
}
</style>
<script>
function showMsg() {
var dom = document.createElement('div');
dom.setAttribute('class', 'x-msg');
dom.innerText = '页面有更新,请刷新页面';
var close = document.createElement('span');
close.setAttribute('class', 'x-close');
close.innerHTML = '<svg style="padding-top: 5px;" aria-hidden="true" width="18" height="18" viewBox="0 0 18 18"><path style="fill: #fff;" d="M15 4.41L13.59 3 9 7.59 4.41 3 3 4.41 7.59 9 3 13.59 4.41 15 9 10.41 13.59 15 15 13.59 10.41 9z"></path></svg>';
close.addEventListener('click', function() {
dom.setAttribute('style', 'display: none');
})
dom.appendChild(close);
document.body.appendChild(dom);
}
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js', {scope: '/'})
.then(function (registration) {
if (registration.installing) {
console.log('正在installing');
}
if (registration.waiting) {
console.log('正在registration.waiting')
}
if (registration.active) {
console.log('已经active')
}
// 注册成功
console.log('ServiceWorker registration successful with scope: ', registration.scope);
})
.catch(function (err) {
// 注册失败:(
console.log('ServiceWorker registration failed: ', err);
});
navigator.serviceWorker.addEventListener('message', function(event) {
console.log(event);
switch(event.data.action) {
case 'has-update':
showMsg();
break;
}
})
});
}
</script>
- 执行
hexo g
即可添加service worker缓存支持
监测到网页变化会有提示
![图片](http://p7ikgz4b9.bkt.clouddn.com/%E5%B1%8F%E5%B9%95%E5%BF%AB%E7%85%A7%202018-10-24%20%E4%B8%8B%E5%8D%8810.16.55.png)