其他分享
首页 > 其他分享> > PWA渐进式web应用

PWA渐进式web应用

作者:互联网

PWA(Progressive Web App)是一种理念,使用多种技术来增强web app的功能,可以让网站的体验变得更好,能够模拟一些原生功能,比如通知推送。在移动端利用标准化框架,让网页应用呈现和原生应用相似的体验。

PWA核心技术

PWA四个核心内容

  1. manifest.json
  2. serviceWork
  3. cacheStrorage
  4. notification

1、manifest

注意点

  1. manifest.json 配置
  2. index.html 中引入manifest.json
  3. 需要https或者http://localhost下访问

常见配置

{
    "name":"电影App",
    "short_name":"app",
    "start_url":"/index.html",
    "icon":[{
        "src":"icons/icon_fro.png",
        "sizes":"144x144",
        "type":"image/png"
    }],
    "background_color":"skyblue",
    "theme_color":"yellow",
    "display":"standalone"
}

2、service worker

web work使用

service worker

  1. 一旦install ,永久存在,除非被手动unregister
  2. 用到的时候唤醒,不用自动休眠
  3. 必须https环境下工作
  4. 异步实现,内不通过Promise实现
  5. 可编程链接代理请求和返回,缓存文件,缓存的文件可以被网页进程取到(包括网络离线状态)

service worker使用步骤

service worker生命周期事件

fetch Api

config常见参数
body
headers
methods
index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入清单文件 -->
    <link rel="manifest" href="manifest.json">
</head>

<body>
    <h1>hello word</h1>
    <!-- web worker -->
    <script>
        const worker = new Worker('worker.js')
        worker.addEventListener('message', e => {
            console.log(e.data)
        })
    </script>
    <!-- service worker -->
    <script>
        // 1.需要网页加载完成注册
        window.onload = () => {
            // 2.能力监测
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('./sw.js').then(res => {
                    console.log(res)
                })
            }
        }
    </script>
</body>

</html>

webwork.js

// 独立的进程,不能做dom操作
let total = 0 
for(var i=0;i<1000000;i++){total+=i}
// 发消息给主线程,把结果给他
self.postMessage({total:total})

sw.js (serviceWorker)

console.log('service注册')
self.addEventListener('install', e => {
    console.log(e)
    /*  
     跳过等待,直接到activite状态 是一个promise
      self.skipWaiting() 
     */

    // 等待skipWaiting结束,activite状态 是一个promise
    e.waitUntil(self.skipWaiting())
})
self.addEventListener('activate', e => {
    //   表示service work激活后,利可获取控制权
    e.waitUntil(self.ClientRectList.claim())
})
self.addEventListener('fatch', e => {
    console.log(e)
})

3、cacheStorage基本使用

api类似于数据库操作

cache常用方法

cache接口缓存的request/response对象提供存储机制

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入清单文件 -->
    <link rel="manifest" href="manifest.json">
</head>
<body>
    <h1>hello word</h1>
    <script>
        window.addEventListener('load', async()=>{
            if('serviceWorker' in navigator){
                try {
                    const registration=await navigator.serviceWorker.register('./sw.js')
                    console.log('成功')
                } catch (error) {
                    console.log('失败')
                }
            }
        })
    </script>
</body>
</html>

sw.js

// 注册serviceWorker时间
const CACHENAME = 'chache_v1'
// 缓存内容
self.addEventListener('install', async (e) => {

    const cache = await caches.open(CACHENAME)
    await cache.addAll([
        '/',
        '/icons/icon_fro.png',
        'manifest.js'
    ])
    e.waitUntil(self.skipWaiting())
})
// 清除就得缓存
self.addEventListener('activate', async e => {
    const keys = await caches.keys()
    keys.forEach(key => {
        if (key == CACHENAME) {
            caches.delete(key)
        }
    })
    e.waitUntil(self.clients.claim())
})
// 请求时间触发
// 能请求:请求
// 不能请求:读取cachesStorage
self.addEventListener('fetch', e => { 
    // 请求对象
const req=e.request
// 给浏览器响应
e.respondWith(networkFirst(req))

})
// 网络有限
async function networkFirst(req){
    try {
        const fresh=await fetch(req)
        return fresh
    } catch (error) {
        // 去缓存读取
        const cache=await caches.open(CACHENAME)
        const cached=await cache.match(req)
        return cached
    }
}

4、notiication 通知

  1. default:未授权
  2. denied:拒绝
  3. granted:授权

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入清单文件 -->
    <link rel="manifest" href="manifest.json">
</head>
<body>
    <h1>hello word</h1>
    <script>
        window.addEventListener('load', async()=>{
            if('serviceWorker' in navigator){
                try {
                    const registration=await navigator.serviceWorker.register('./sw.js')
                    console.log('成功')
                } catch (error) {
                    console.log('失败')
                }
            }
        })
        // 判断是否联网
        if(Notification.permission=='default'){
            // 请求提示权限
            Notification.requestPermission()
        }
        if(!navigator.onLine){
            new Notification('提示',{body:'当前没有网'})
        }
        window.addEventListener('online',e=>{
            new Notification('提示',{body:'又忘了,请刷新访问最新数据'})
   
        })
    </script>
</body>
</html>

静态资源缓存优先,动态数据请求有限

标签:web,缓存,service,self,cache,worker,渐进式,serviceWorker,PWA
来源: https://www.cnblogs.com/ypSharing/p/PWA.html