TheFullResolution TheFullResolution - 5 months ago 19
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' });
return;
}

reg.addEventListener('updatefound', function() {
trackInstalling(reg.installing);
});

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

});

}


Cache is listed like this:

var urlsToCache = [
'/',
'/index.html',
'/css/app.min.css',
'/js/app.min.js',
'/js/library.min.js',
'/views/line.html',
'/views/start.html',
'/views/station.html',
'/views/timetable.html'
];


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
'train/index.html'
the service worker is looking for
'train/train/index.html'
. 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?

Answer

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.
    'css/app.min.css',
    'js/app.min.js',
    'js/library.min.js',
    'views/line.html',
    'views/start.html',
    'views/station.html',
    'views/timetable.html'
];
Comments