T
T
takoyklasnii2020-01-15 13:26:20
JavaScript
takoyklasnii, 2020-01-15 13:26:20

Why does the site crash when caching files during PWA, when offline?

I have a backend on LARAVEL (api) and a front-end on React. The task is to build a PWA.
There is a connection to service-worker.js in app.js:

if ("serviceWorker" in navigator) {
  console.log("В условии");
  window.addEventListener("load", () => {
    navigator.serviceWorker.register("/service-worker.js").then(
      reg => {
        console.log("worked!");
      },
      err => {
        console.log("Error", err);
      }
    );
  });
} else {
  console.log("service worker is not supported");
}

There is service-worker.js itself:
let CACHE_NAME = "-cache";

let cachedUrl = [
  "/js/app.js",
  "/css/app.css",
  "/css/styles.css",
];

self.addEventListener("install", event => {
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      console.log("Кеш открыт, install событие! Пробуем кешировать!");
      return cache.addAll(cachedUrl);
    })
  );
});

self.addEventListener("fetch", event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      if (response) {
        return response;
      }

      return fetch(event.request);
    })
  );
});

self.addEventListener("activate", event => {
  let cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheWhitelist.indexOf(cacheName)) {

            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

Why if I cut off the Internet, the application crashes? Or do you need to connect offline pages that will work offline?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arthur, 2020-01-15
@ar2rsoft

You added only js, css to the cache. You need to add the pages themselves

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question