PWA之server-worker

  • server-worker想要本地测试的话,需要的ip必须是localhost或者127.0.0.1
  • server-worker的使用必须是在https协议下
  • test.js
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>server worker</title>
</head>

<body>
</body>
<script>
  if ('serviceWorker' in navigator) {
    var version = '1.0.1'
    window.addEventListener('load', function () {
      navigator.serviceWorker.ready.then(registration => {
        console.log(registration)
      }).catch(err => {
        console.log(err)
      })

      navigator.serviceWorker.register('/test/test1-css/test.js', {
        scope: '/test/test1-css/'
      }).then(function (registration) {
        // worker文件(test.js)可能会因为浏览器缓存问题,当文件有了变化时,浏览器里还是旧的文件。这会导致更新得不到响应。
        if (localStorage.getItem('sw_version') !== version) {
          registration.update().then(function () {
            localStorage.setItem('sw_version', version)
          })
        }
        // 注册成功
        console.log('ServiceWorker registration successful with scope: ', registration.scope)
      }).catch(function (err) {
        // 注册失败:
        console.log('ServiceWorker registration failed: ', err)
      })
    })
  }
</script>

</html>
  1. 监听 service worker 的 install 事件

    // on install 的优点是第二次访问即可离线,缺点是需要将需要缓存的 URL 在编译时插入到脚本中,增加代码量和降低可维护性

    // 监听 service worker 的 install 事件
      // on install 的优点是第二次访问即可离线,缺点是需要将需要缓存的 URL 在编译时插入到脚本中,增加代码量和降低可维护性;
      const ENV = 'development'
      this.addEventListener('install', function (event) {
        console.log('test')
        // 本地开发时希望重新加载后立即激活
        if (ENV === 'development') {
          self.skipWaiting()
          return true
        }
        // 如果监听到了 service worker 已经安装成功的话,就会调用 event.waitUntil 回调函数
        event.waitUntil(
          // 安装成功后操作 CacheStorage 缓存,使用之前需要先通过 caches.open() 打开对应缓存空间。
          caches.open('my-test-cache-v1').then(function (cache) {
            console.log('cache:', cache)
            // 通过 cache 缓存对象的 addAll 方法添加 precache 缓存
            // 以下资源被加载过一次之后将开始被缓存
            return cache.addAll(['/test/test1-css/index.html', '/test/test1-css/index2.html'])
          }).catch(function (err) {
            console.log(err)
          })
        )
      })

2.on fetch 的优点是无需更改编译过程,也不会产生额外的流量,缺点是需要多一次访问才能离线可用。
 

this.addEventListener('fetch', function (event) {
    event.respondWith(
      caches.match(event.request).then(function (response) {
        // 来来来,代理可以搞一些代理的事情
        console.log(response)
        // 如果 Service Worker 有自己的返回,就直接返回,减少一次 http 请求
        if (response) {
          return response
        }
        // 如果 service worker 没有返回,那就得直接请求真实远程服务
        var request = event.request.clone()
        // 把原始请求拷过来
        return fetch(request).then(function (httpRes) {
          // http请求的返回已被抓到,可以处置了。
          console.log(httpRes)
          // 请求失败了,直接返回失败的结果就好了。
          if (!httpRes || httpRes.status !== 200) {
            return httpRes
          }
          // 请求成功的话,将请求缓存起来。
          var responseClone = httpRes.clone()
          caches.open('my-test-cache-v1').then(function (cache) {
            cache.put(event.request, responseClone)
          })
          return httpRes
        })
      })
    )
  })

3. 安装阶段跳过等待,直接进入 active,如果希望在有了新版本时,所有的页面都得到及时自动更新
 

self.addEventListener('install', function (event) {
    event.waitUntil(self.skipWaiting())
  })
  self.addEventListener('activate', function (event) {
    event.waitUntil(
      Promise.all([
        // 更新客户端      
        self.clients.claim(),
        // 清理旧版本      
        caches.keys().then(function (cacheList) {
          return Promise.all(
            cacheList.map(function (cacheName) {
              if (cacheName !== 'my-test-cache-v1') {
                return caches.delete(cacheName)
              }
            }))
        })]))
  })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Server-Side Enterprise Development with Angular: Use Angular Universal to pre-render your web pages, improving SEO and application UX By 作者: Bram Borggreve ISBN-10 书号: 1789806267 ISBN-13 书号: 9781789806267 出版日期: 2018-11-29 pages 页数: (223) With the help of Server-Side Enterprise Development with Angular, equip yourself with the skills required to create modern, progressive web applications that load quickly and efficiently. This fast-paced book is a great way to learn how to build an effective UX by using the new features of Angular 7 beta, without wasting efforts in searching for referrals. To start off, you’ll install Angular CLI and set up a working environment, followed by learning to distinguish between the container and presentational components. You’ll explore advanced concepts such as making requests to a REST API from an Angular application, creating a web server using Node.js and Express, and adding dynamic metadata. You’ll also understand how to implement and configure a service worker using Angular PWA and deploy the server-side rendered app to the cloud. By the end of this book, you’ll have developed skills to serve your users views that load instantly, while reaping all the SEO benefits of improved page indexing. Contents What You Will Learn Identify what makes an Angular application SEO-friendly Generate commands to create components and services Distinguish between the container and presentational components Implement server-side rendering using Angular Universal Create a web server using Node.js and Express Add dynamic metadata to your web application Deploy a server-side rendered app to the cloud Implement and configure a service worker using Angular PWA Authors Bram Borggreve Bram Borggreve is a software engineer from the Netherlands, who currently works as an instructor at egghead.io, and is the founder of Colmena Consultancy. With almost 20 years of experience in all fields of the software lifecycle, Bram has a complete overview of the high-value challenges that clients are keen to resolve.
vite-plugin-pwa是一个vite的官方插件,它可以通过简单的配置将你的vite项目转变成一个PWA(Progressive Web App)应用。它使用谷歌开源库workbox来实现service worker的功能,并为缓存做了大量的逻辑代码处理,同时还支持多种不同的缓存策略。此外,vite-plugin-pwa还提供了更新sw.js文件的策略,并且它的配置非常简单。使用vite-plugin-pwa可以使你的应用具备离线访问、消息推送等PWA的特性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vite-plugin-pwa:Vite的零配置PWA](https://download.csdn.net/download/weixin_42115074/15088884)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [vite-plugin-pwa配置详解](https://blog.csdn.net/YMX2020/article/details/130882745)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [vite pwa项目使用](https://blog.csdn.net/qq_40055200/article/details/130857483)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值