Service Worker的基本使用

环境准备

安装http-server

npm install -g http-server


准备index.html


<head>
  <title>Minimal PWA</title>
  <meta name="viewport" content="width=device-width, user-scalable=no" />
  <link rel="manifest" href="manifest.json" />
  <link rel="stylesheet" type="text/css" href="main.css">
  <link rel="icon" href="/e.png" type="image/png" />
</head>


<body>
  <div class="revision">Revision 8</div>
  <img src="pwa-fonts.png">
  <div class="main-text">
    Minimal PWA, open Console for more!
  </div>
  <div class="network-message">
    Network:
    <span id="network-status" class="">Good</span>
  </div>
  <script type="text/javascript">
    if (navigator.serviceWorker != null) {
      navigator.serviceWorker.register('sw.js')
      .then(function(registration) {
        console.log('Registered events at scope: ', registration.scope);
      });
    }


    fetch('./data.json')


    var statusEl = document.querySelector('#network-status')
    if (!navigator.onLine) {
      statusEl.classList = ['is-offline']
      statusEl.innerText = 'Offline'
    }
  </script>
</body>


准备css文件main.css


body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: Helvetica Neue;
  font-weight: 200;
  font-size: 20px;
  background-color: #313131;
  background-image: radial-gradient(ellipse farthest-corner at 45px 45px ,
                        hsla(0,80%,100%,0.32) 0%,
                        hsla(0,80%,80%,0.16) 60%,
                        hsla(0,80%,80%,0) 95%);
  color: #ccc;
}


.main-text {
  white-space: nowrap;
}


img {
  width: auto;
  max-width: 80%;
}


.revision {
  font-weight: 200;
  position: fixed;
  top: 32px;
  left: 32px;
}


.network-message {
  font-weight: 200;
  position: fixed;
  bottom: 32px;
  right: 32px;
}


准备manifest.json, 用于生成桌面快捷方式

{
  "name": "Minimal PWA",
  "short_name": "PWA Demo",
  "display": "standalone",
  "start_url": "/",
  "theme_color": "#313131",
  "background_color": "#313131",
  "icons": [
    {
      "src": "e.png",
      "sizes": "256x256",
      "type": "image/png"
    }
  ]
}



准备service worker文件sw.js


console.log('Script loaded!')

//缓存仓库名字
var cacheStorageKey = 'minimal-pwa-8'  

//需要缓存的文件
var cacheList = [
  '/',
  "index.html",
  "main.css",
  "e.png",
  "pwa-fonts.png"
]

//处理安装事件
self.addEventListener('install', function(e) {
  console.log('Cache event!')
  e.waitUntil(
    caches.open(cacheStorageKey).then(function(cache) {
      console.log('Adding to Cache:', cacheList)
      return cache.addAll(cacheList)
    }).then(function() {
      console.log('Skip waiting!')
      return self.skipWaiting()
    })
  )
})

//处理activate事件
self.addEventListener('activate', function(e) {
  console.log('Activate event')
  e.waitUntil(
    Promise.all(
      caches.keys().then(cacheNames => {
        return cacheNames.map(name => {
          if (name !== cacheStorageKey) {
            return caches.delete(name)
          }
        })
      })
    ).then(() => {
      console.log('Clients claims.')
      return self.clients.claim()
    })
  )
})

//处理fetch事件
self.addEventListener('fetch', function(e) {
  // console.log('Fetch event:', e.request.url)
  e.respondWith(
    caches.match(e.request).then(function(response) {
      if (response != null) {
        console.log('Using cache for:', e.request.url)
        return response
      }
      console.log('Fallback to fetch:', e.request.url)
      return fetch(e.request.url)
    })
  )
})


运行http-server

http-server -p 8000 -c-1



首次访问从网络下载页面



停掉http-server,一样可以正常访问



通过chrome dev tools查看service workers



查看Cache Storage




移动端访问,可以通过ngrok工具来完成



加上AppShell就是一个完整的PWA应用。


参考资料

https://zhuanlan.zhihu.com/p/25459319

https://kymjs.com/code/2017/02/15/01/

https://kymjs.com/code/2017/02/18/01/

https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker

https://developers.google.com/web/fundamentals/getting-started/codelabs/your-first-pwapp/?hl=zh-cn#progressive_web_app


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值