0.1.6 • Published 6 years ago

hexo-cache v0.1.6

Weekly downloads
1
License
ISC
Repository
github
Last release
6 years ago

hexo-cache

用于hexo博客添加service worker缓存支持 1. 安装

npm install hexo-cache --save
  1. 给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>
  1. 执行 hexo g 即可添加service worker缓存支持

监测到网页变化会有提示

图片

0.1.6

6 years ago

0.1.5

6 years ago

0.1.4

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

0.0.1

6 years ago