Search code examples
cachingservice-workerworkbox

Use of self.clients.claim() and self.skipWaiting() in service worker may increase the load time?


After reading many tutorials, I founded that self.skipWaiting() is used to immediately apply an update to an existing serviceWorker, and self.clients.claim() is used for taking control immediately on the first load.

self.addEventListener('install', function(event) {
    event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function(event) {
    event.waitUntil(self.clients.claim());
});

Is it lookup for update on every request or how does it work internally? Use of self.clients.claim() and self.skipWaiting() is any impact on load or service worker performance?


Solution

  • There's no impact from a performance perspective.

    Both self.skipWaiting() and self.clients.claim() work by taking some action and, at the same time, immediately resolving with an undefined value.

    In the case of self.skipWaiting(), the action that's taking is effectively just flipping an internal flag and causing the service worker to attempt to activate. In the case of self.clients.claim(), the action is to go through all the clients and attempt to have the currently executing service worker take control.

    The actual promise that's returned by both of those methods is irrelevant, and you don't have to wrap them in event.waitUntil() (although it doesn't hurt, and many examples of service worker usage continue to do so).

    Additionally, because your code is only making calls to those methods inside of install and activate listeners, the code in question won't even execute most of the time that the service worker thread starts up—only when there's an updated service worker.