yeoman/generator-webapp

Service Worker with yeoman webapp

mrassili opened this issue · 2 comments

My project structure looks something this :

.tmp
    scripts
        bundle.js
        bundle.map.js
app
    scripts
        main.js
    styles
        buttons.scss
        grid.scss
        ....
        main.scss
    index.html
    sw.js

My service worker registration :

// Register Service Worker
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js')
    .then(reg => console.log("Registration successful"))
    .catch(() => console.log("Registration failed"));
  }

I wanna use Service Worker to make an offline web app, I cached the resources and implemented the code to serve them on fetch events, but although they aren't served and I keep getting this error The FetchEvent for "http://localhost:9000/" resulted in a network error response: the promise was rejected. and failed to fetch. I'm using localhost with gulp serve for dev. I think the service worker should be placed somewhere else, like .tmp maybe?? what do you think?

My sw.js file :

const staticCache = "staticCache-v1";
const staticAssets = [
  //js
  "browser-sync/browser-sync-client.js?v=2.24.5",
  "index.html",
  "scripts/bundle.js",
  //css
  "styles/main.scss",
  //html
  "index.html",
  //fonts
  "https://fonts.gstatic.com/s/sourcesanspro/v11/6xK3dSBYKcSV-LCoeQqfX1RYOo3qNa7lujVj9_mf.woff2",
  "https://free.currencyconverterapi.com/api/v5/currencies"
];

self.addEventListener("install", event => {
  // Cache static resources
  event.waitUntil(
    caches.open(staticCache).then(cache => cache.addAll(staticAssets))
  );
});

self.addEventListener("activate", event => {
  // clean old SW
});

self.addEventListener("fetch", event => {
  // try placing the sw in .tmp
  console.log("fetch request :", event.request);
  event.respondWith(
    caches.match(event.request).then(cacheResponse => {
      return cacheResponse || fetch(event.request);
    })
  );
});

I solved the problem, I had to use relative paths by having a leading dot in all urls to be cached.
This issue can be closed.

@mrassili nice that you solved the problem