DEV Community

Cover image for One domain - multiple service-worker up
jswalker.in
jswalker.in

Posted on • Updated on

One domain - multiple service-worker up

What dilemma i faced?

I usually keep working on multiple projects but with full attention on one project at a specific time(Week, Month). But for a minimal update, I usually follow the same procedure that keeps an offline app with a service worker.
If you are a soloprenuer and have a cash crunch at an early stage, you have to deal with multiple apps under one domain.

like I am doing multiple apps(Total 10) with jswalker.in under /its/ tag and 7 with a subdomain.

If you follow approach from this URL.You will get few gotchas in work-cycle.

Service worker activate event


var staticCacheName="appname_version_1";
self.addEventListener('activate', function(event) {
  var cacheWhitelist = [staticCacheName];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
           console.log("Cache delete : "+key);
           return caches.delete(key);
        }

      }));

    })
  );

Enter fullscreen mode Exit fullscreen mode

Root Cause of problem

If we use previous approach We will face no problem and no other cache version will be affected of sub domain's service worker.

But if you use the same domain with dynamic URLs like: /its/amazing and its/sweeper as different Progressive web app.Previous service-worker strategy makes your Eco-System a little bit vulnerable at the offline stage.

It will clear every cache-list except current app-version.In that case if one of your app got update it will remove all caches(10 APP cache) it means /first-app,/second-app cache will also got removed.But service worker still not Unregister from browser so now network request of PWA not found in caches.keys() and make request over Network not from Service-Worker.

How to resolve?

var staticCacheName='appname_version_2';
self.addEventListener('activate', function(event) {

  var static_cache_prefix = staticCacheName.substring(0,staticCacheName.indexOf("_"));

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {

        if (key.indexOf(static_cache_prefix) > -1 && key!=staticCacheName) { 
           console.log("Cache delete : "+key);
           return caches.delete(key);
        }

      }));

    })
  );
});

Enter fullscreen mode Exit fullscreen mode

What you will achieve?

The above strategy will check appname in cache list AKA caches.keys().Now it will only remove cache of specific app(separated by URL) with old version and all other related app cache will intact along with new version of updated PWA.

Top comments (0)