TheFullResolution TheFullResolution - 3 months ago 8
Javascript Question

Registering Service Worker in a different folder

I am trying to figure how to register properly service worker, in development all works fine, I call service worker:

if (navigator.serviceWorker) {
navigator.serviceWorker.register('./sw.js').then(function(reg) {
if (reg.waiting) {
reg.waiting.postMessage({ action: 'skipWaiting' });

reg.addEventListener('updatefound', function() {

var refreshing;
navigator.serviceWorker.addEventListener('controllerchange', function() {
if (refreshing) return;
refreshing = true;



Cache is listed like this:

var urlsToCache = [

This is just a project I am doing for Udacity so the page won't have it's own domain. However I still want to keep the final version on-line in a folder /train/ but service worker is registered under the main domain so is caching wrong files.

If I add
the service worker is looking for
. Same happens if try to register service worker in a folder "train"...

How should I do it so the on-line version of the project works properly?


Since your service worker will now live in a subfolder of the domain, its cache paths should be relative:

var urlsToCache = [
    './',  // I'm not 100% sure on the syntax for this one. In your case
           // '/train/' would definitely work, but it would require updating
           // if you ever move the app to a different folder.

    'index.html', // All the other URLs just lose their preceding slash.