首页 > 解决方案 > 服务工作者在每个子 URL 上注册

问题描述

我有一个带有服务人员的站点,每次访问新的子 URL 时它都会注册。这是预期的行为吗?

例子。我的根 URL 是mysite.com. 当我访问该 URL 时,软件注册正常。当我访问时mysite.com/subpage,它也会注册为该 URL 的新服务工作者。

如果我做错了什么,或者这是否是 SW 的工作方式,请告诉我。

我的服务工作者每次安装时都会重新缓存资源,所以我猜它会在用户第一次访问子 URL 时重新缓存所有内容。不是不推荐吗?

这是我的软件。

var staticCacheName = "bspev-v" + new Date().getTime();
var filesToCache = [
  '/',
  '/offline',
  '/css/app.css',
  '/js/app.js',
  '/js/rutas.js',

  // iconos app
  '/images/icons/icon-72x72.png',
  '/images/icons/icon-96x96.png',
  '/images/icons/icon-128x128.png',
  '/images/icons/icon-144x144.png',
  '/images/icons/icon-152x152.png',
  '/images/icons/icon-192x192.png',
  '/images/icons/icon-384x384.png',
  '/images/icons/icon-512x512.png',
  '/favicon.ico',

  // imagenes app
  '/images/logotexto.png',
  '/images/offline.png',

  // ajax
  '/api/prestamos/pendientes',

  //fuentes app
  'https://fonts.googleapis.com/css?family=Archivo+Narrow&display=swap',
  'https://fonts.gstatic.com/s/archivonarrow/v11/tss0ApVBdCYD5Q7hcxTE1ArZ0bbwiXw.woff2',

  // vue
  '/js/vue.js',
  '/js/vue.min.js',

  // fontawesome
  '/css/fa-all.css',
  '/webfonts/fa-solid-900.woff2'
];


// Cache on install
self.addEventListener("install", event => {
    this.skipWaiting();
    event.waitUntil(
        caches.open(staticCacheName)
            .then(cache => {
                console.log('Service Worker instalado.');
                return cache.addAll(filesToCache);
            })
    )
});

// Clear cache on activate
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames
                    .filter(cacheName => (cacheName.startsWith("bspev-")))
                    .filter(cacheName => (cacheName !== staticCacheName))
                    .map(cacheName => caches.delete(cacheName))
            );
        })
    );
});


// Serve from Cache
self.addEventListener("fetch", event => {
    const requestURL = new URL(event.request.url);

    //Handle api calls
    if (/\/api\//.test(requestURL.pathname)) {
        event.respondWith(
            fetch(event.request).then(response => {
                event.waitUntil(
                    caches.open(staticCacheName).then(cache => {
                      cache.put(event.request, response.clone());
                    })
                );
                return response.clone();
            }).catch(function() {
            return caches.match(event.request);
          })
        );
    } else {
      event.respondWith(
          caches.match(event.request)
              .then(response => {
                  return response || fetch(event.request);
              })
              .catch(() => {
                  return caches.match('offline');
              })
      );

    }
});

这是软件注册

<script type="text/javascript">
    // Initialize the service worker
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/serviceworker.js', {
            scope: '.'
        }).then(function (registration) {
            // Registration was successful
            console.log('Laravel PWA: ServiceWorker registration successful with scope: ', registration.scope);
        }, function (err) {
            // registration failed :(
            console.log('Laravel PWA: ServiceWorker registration failed: ', err);
        });
    } else { console.log('no serviceWorker in navigator') }
</script>

标签: service-workerprogressive-web-apps

解决方案


推荐阅读