ServiceWorker 缓存策略
ServiceWorker 缓存策略
浮川的小窝

ServiceWorker 缓存策略

面壁人浮川
2024-03-14 / 0 评论 / 6 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年03月14日,已超过63天没有更新,若内容或图片失效,请留言反馈。

def3dc08-serviceworker-darstellung-1.png


项目中用到了ServiceWorker 在离线环境中能够加载出最新的文件缓存 避免直接大白瓶或显示404无法访问;在首次首页加载后,也将大部分资源缓存下来,增加后续网站渲染速度,增加用户体验
使用过程中遇到了一个坑 表情

const plugins = [
  new GenerateSW({
    cacheId: 'hwork-portal',
    swDest: 'service-worker.js',
    sourcemap: false,
    clientsClaim: true,
    skipWaiting: true,
    cleanupOutdatedCaches: true,
    // maximumFileSizeToCacheInBytes: 2621440, // 2.5Mb,默认值是 2097152(2Mb)
    runtimeCaching: [{
      handler: 'CacheFirst',
      options: {
        cacheName: 'js'
      },
      urlPattern: ({ event, request, sameOrigin, url }) => {
        const pathname = url.pathname || ''
        if (pathname.includes('xxx')) {
          const file = pathname.split('?')[0] || ''
          const fileType = file.split('.')[1] || ''

          if (fileType === 'js') {
            return true
          }
        }
      }
    }, {
      handler: 'CacheFirst',
      options: {
        cacheName: 'css'
      },
      urlPattern: ({ event, request, sameOrigin, url }) => {
        const pathname = url.pathname || ''

        if (pathname.includes('xxx')) {
          const file = pathname.split('?')[0] || ''
          const fileType = file.split('.')[1] || ''

          if (fileType === 'css') {
            return true
          }
        }
      }
    }, {
      handler: 'StaleWhileRevalidate',
      options: {
        cacheName: 'images'
      },
      urlPattern: ({ event, request, sameOrigin, url }) => {
        const pathname = url.pathname || ''

        if (pathname.includes('xxx')) {
          const file = pathname.split('?')[0] || ''
          const fileType = file.split('.')[1] || ''

          if (['webp', 'png', 'jpg'].includes(fileType)) {
            return true
          }
        }
      }
    }]
  }),

上面是webpack中的部分plugins配置 由于项目使用的是微前端 所以最上级应用中配置了sw.js 加载二级应用时 发现了一个很奇怪的现象 js存在缓存的情况下是正常的 当有缓存时直接返回缓存值 但是css就很奇怪了 有缓存 但是sw还是又重新发起了一遍fetch请求 然后我就一通找啊找 表情 表情
最后经过部门老大的提示 发现是二级应用打包的时候 base路径的三级域名并没有跟最上级应用一样 至于不同域名下js为啥能加载出来 目前没有找到原因 但是改过打包后 情况就正常了特此记录一下

0

评论 (0)

取消