Кэшированный файл не извлекается сервисным работником

Когда я пытаюсь получить доступ http://localhost/visites/ он должен получить предварительно кэшированный файл visites/index.php. Итак, я думаю, мне нужно где-то указать, что этот конкретный маршрут соответствует этому файлу, вы знаете, как я могу это сделать?

Я оставляю здесь свой программный код на всякий случай:

      const cacheName = 'v1';

const cacheAssets = [
    'accueil.php',
    'js/accueil.js',
    'visites/index.php',
    'js/visites.js',
    'js/global.js',
    'css/styles.css',
    'charte/PICTOS/BTN-Visites.png',
    'charte/STRUCTURE/GESTEL-Logo.png',
    'charte/PICTOS/BTN-Animaux.png',
    'charte/PICTOS/BTN-Deconnexion.png',
    'charte/PICTOS/BTN-Fermes.png',

];

// Call Install Event
self.addEventListener('install', e => {
  console.log('Service Worker: Installed');

  e.waitUntil(
    caches
      .open(cacheName)
      .then(cache => {
        console.log('Service Worker: Caching Files');
        cache.addAll(cacheAssets);
      })
      .then(() => self.skipWaiting())
  );
});

// Call Activate Event
self.addEventListener('activate', e => {
  console.log('Service Worker: Activated');
  // Remove unwanted caches
  e.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if (cache !== cacheName) {
            console.log('Service Worker: Clearing Old Cache');
            return caches.delete(cache);
          }
        })
      );
    })
  );
});

// Call Fetch Event
self.addEventListener('fetch', e => {
  console.log('Service Worker: Fetching');
  e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
})

1 ответ

Вы можете включить логику в свой fetch обработчик, который учитывает эту информацию о маршрутизации:

      self.addEventListener('fetch', e => {
  // Use a URL object to simplify checking the path.
  const url = new URL(e.request.url);

  // Alternatively, check e.request.mode === 'navigate' if
  // you want to match a navigation to any URL on your site.
  if (url.pathname === '/visites/') {
    e.respondWith(caches.match('visites/index.php'));
    // Return after responding, so that the existing
    // logic doesn't get triggered.
    return;
  }

  e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
});
Другие вопросы по тегам