service worker实现静态资源缓存

service worker如何实现静态资源缓存和强制更新,请看如下示例:

1、注册service worker

复制代码
function serviceWorker() {
  if (isLocalStorageAvailable() && 'serviceWorker' in navigator) {
    navigator.serviceWorker.register('/static/almasaeed2010/adminlte/dist/js/service-worker.js')
      .then(registration => {
        console.log('Service Worker 注册成功:', registration);
      })
      .catch(error => {
        console.log('Service Worker 注册失败:', error);
      });
  }
}

2、worker实现:

复制代码
// 预定义要缓存的文件列表
const cacheName = 'fbspider-cache-v1.1.2';
//update time
const filesToCache = [
  '/static/almasaeed2010/adminlte/plugins/jquery/jquery.min.js',
  '/static/almasaeed2010/adminlte/plugins/jquery-ui/jquery-ui.min.js',
  '/static/almasaeed2010/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js',
  '/static/almasaeed2010/adminlte/plugins/moment/moment.min.js',
  '/static/almasaeed2010/adminlte/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js',
  '/static/almasaeed2010/adminlte/dist/js/adminlte.js',
  '/static/almasaeed2010/adminlte/plugins/sweetalert2/sweetalert2.min.js',
  '/static/almasaeed2010/adminlte/plugins/toastr/toastr.min.js',
  '/static/almasaeed2010/adminlte/dist/js/demo.js',
  '/datatables-responsive/js/responsive.bootstrap4.min.js',
  'https://cdn.datatables.net/fixedcolumns/3.3.3/js/dataTables.fixedColumns.min.js',
  '/static/almasaeed2010/adminlte/plugins/datatables-buttons/js/buttons.bootstrap4.min.js',
  '/static/almasaeed2010/adminlte/plugins/datatables-buttons/js/dataTables.buttons.min.js',
  '/static/almasaeed2010/adminlte/plugins/datatables-responsive/js/dataTables.responsive.min.js',
  '/static/almasaeed2010/adminlte/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js',
  '/static/almasaeed2010/adminlte/plugins/datatables/jquery.dataTables.min.js',
  '/static/almasaeed2010/adminlte/plugins/fontawesome-free/css/all.min.css',
  '/static/almasaeed2010/adminlte/plugins/icheck-bootstrap/icheck-bootstrap.min.css',
  '/static/almasaeed2010/adminlte/dist/css/adminlte.min.css',
  //'/static/almasaeed2010/adminlte/dist/css/common.css',
  '/static/almasaeed2010/adminlte/plugins/sweetalert2-theme-bootstrap-4/bootstrap-4.min.css',
  '/static/almasaeed2010/adminlte/plugins/toastr/toastr.min.css',
  '/static/almasaeed2010/adminlte/plugins/overlayScrollbars/css/OverlayScrollbars.min.css',
  '/static/almasaeed2010/adminlte/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css',
  '/static/almasaeed2010/adminlte/plugins/datatables-responsive/css/responsive.bootstrap4.min.css',
  '/static/almasaeed2010/adminlte/plugins/datatables-buttons/css/buttons.bootstrap4.min.css',
  'https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css',

  // ...其他文件
];

// 在 Service Worker 安装阶段缓存文件-----
self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return Promise.all(
        filesToCache.map(function(file) {
          return cache.add(file).catch(function() {
            console.log('Failed to cache:', file);
          });
        })
      );
    })
  );
  self.skipWaiting();
});


// 拦截网络请求并返回缓存的响应(如果存在)
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // 如果缓存中有该请求,返回缓存的响应
        if (response) {
          return response;
        }
        // 否则,进行实际的网络请求
        return fetch(event.request);
      })
  );
});
self.addEventListener('activate', function(event) {
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(thisCacheName) {
          // 如果一个存在的缓存不匹配当前缓存名称,就删除它
          if (thisCacheName !== cacheName) {
            return caches.delete(thisCacheName);
          }
        })
      );
    })
  );
});

3、如何实现客户端浏览器强制刷新缓存:

网上的一些方法试过都不生效,我的最终解决方法是强制刷新,至于什么时机刷新,可以在注册完后,在成功的回调方法中,判断并强制刷新,强制刷新如下:

复制代码
registration.update();

可以基于浏览器的localStorage,来决定什么时候刷新。

相关推荐
Byron070736 分钟前
Vue 中使用 Tiptap 富文本编辑器的完整指南
前端·javascript·vue.js
css趣多多1 小时前
地图快速上手
前端
zhengfei6111 小时前
面向攻击性安全专业人员的一体化浏览器扩展程序[特殊字符]
前端·chrome·safari
码丁_1171 小时前
为什么前端需要做优化?
前端
Mr Xu_2 小时前
告别硬编码:前端项目中配置驱动的实战优化指南
前端·javascript·数据结构
Byron07072 小时前
从 0 到 1 搭建 Vue 前端工程化体系:提效、提质、降本实战落地
前端·javascript·vue.js
哆啦code梦2 小时前
前端存储三剑客:localStorage、sessionStorage与Cookie解析
前端·前端存储
老师用之于民2 小时前
【DAY21】Linux软件编程基础&Shell 命令、脚本及系统管理实操
linux·运维·chrome·经验分享·笔记·ubuntu
徐小夕@趣谈前端2 小时前
Web文档的“Office时刻“:jitword共建版2.0发布!让浏览器变成本地生产力
前端·数据结构·vue.js·算法·开源·编辑器·es6
Data_Journal3 小时前
如何使用 Python 解析 JSON 数据
大数据·开发语言·前端·数据库·人工智能·php