封装sw.js

 
 // install 主要就是缓存内容
 const  CACHE_NAME = 'cahe_v1'
 const URLS = [
     '/',
     '/index.css',
     '/images/1.png',
     '/index.js',
     '/manifest.json',
     '/api/66462d0145d352edf611'
 ]
 self.addEventListener('install', async event => {
    // 开启一个 cache
    const cache = await caches.open(CACHE_NAME)
    // cache 对象可以存储资源   :   / 代表 index.html
    await cache.addAll(URLS)  
    await self.skipWaiting()
 })

 // 清除旧的缓存
 self.addEventListener('activate', async event => {  
    // 清除 旧的资源 获取所有的资源的 key
    const keys = await caches.keys()
    keys.forEach(key=>{
        if(key !== CACHE_NAME){
            caches.delete(key)
        }
    })
    await self.clients.claim()
})
 

// fetch 事件会在请求发送的时候触发
// 判断资源否能够请求成功 , 如果能请求成功 就响应成功的结果
// 如果断网 请求失败,就读取 caches 缓存的内容
self.addEventListener('fetch', event => {
   
    // 1 只缓存同源的内容
    const req = event.request
    const url = new URL(req.rul)
    if(url.origin !== self.origin){
        return
    }

    if(req.rul.includes('/api')){
        event.respondWith(netWorkFirst(event.request))
    }else{
        event.respondWith(cacheFirst(event.request))
    }
 
   
})


// 缓存优先 一般适用于静态资源
async function cacheFirst(){
    const cache = await caches.open(CACHE_NAME)
    const cached = await cache.match(req)
    // 如果得到了 就直接返回
    if(cached){
       return cached
    }else{
       const fresh = await fetch(req)
       return fresh
    }
}


// 网络优先 如果获取到了数据,应该往 缓存中 保存一份数据
async function netWorkFirst(req){
    const cache = await caches.open(CACHE_NAME)
    try{
       // 先从网络读取资源
       const fresh = await fetch(req)
       // 获取到的数据 保存缓存
       // 把响应的备份存储到 缓存中
       cache.put(req,fresh.clone())
       return fresh
    } catch (e) {
        // 去缓存中读取
        const cached = await cache.match(req)
        return cached
    }
   
}


posted @ 2022-02-07 15:26  13522679763-任国强  阅读(223)  评论(0)    收藏  举报