[w3c/ServiceWorker] New "setup" lifecycle for service worker (#1576)

Summary: Current, service worker only has install and active lifecycle. I suggest adding a setup lifecycle event, like setup() method in unit testing. When SW wake up by events, it first waits for the setup method complete, then start to process events. setup method only execute once when SW wake up.

Maybe you know service worker now used to process Chrome extension's background event, e.g. browser tabs updates.

```
var initWaitList = [];
var start = false;
var cache;
function init() {
  return new Promise(async function(resolve, reject) {
    if(cache) {
      resolve();
    } else {
      initWaitList.push(resolve);
      if(!start) {
        start = true;
        cache = await readDataFromStorage();
        for(let r of initWaitList) {
          r();
        }
        initWaitList = [];
      }
    }
  });
}

chrome.tabs.onUpdated.addListener(function(parameters) {
  await init();
  // then use cache data process events
});

```
What I understand is that service worker usually keep alive for a while(e.g. 10 seconds) when no task, so use global variable as cache can improve performance, because maybe there will be more events triggered. Cache is the same life cycle with service worker. In above example code, it is a data that async read from storage(IDB or chrome.storage). In my environment(chrome extension), service worker will wake up by multiple events in very short time. The above code(init method) is used to prevent from reading data from storage multiple times, reading multiple times is not necessary.

If service worker support a setup stage before process events, developers don't need to consider concurrent situation before it start to process events.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1576

Received on Tuesday, 6 April 2021 11:56:11 UTC