Long time waiting Request to Service Worker

2019-06-15 06:53发布

问题:

I have noticed that the time waiting for service workers to respond with items from the cache is not as fast as you would expect it to be. I have seen the same wait times with both sw-precache and a custom written service worker.

What are the possible causes for this wait time time and how could I reduce it?

My fetch event on the custom service worker looks like:

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request).then(function(response) {
            if (response) {
                return response;
            }
            return fetch(event.request);
        })
    );
});

回答1:

Do you have 'Update on reload' checked within your Chrome Dev Tools under the Application -> Service Worker tab?

If so then I think this may be the problem as it'll be re-running all your Service Worker code, which can be quite a lot of code when using sw-precache, on each reload.



回答2:

Event though I can't answer the possible causes for this strange wait time, I do know how to reduce it.

We are able to intercept a fetch event in service worker with event.respondWith(). Somehow, in my case, when my page needs to load a vendor's javascript via script tag with my service worker defaults to intercept every fetch event to perform cache-then-network (for assets) or network-only (for data fetching) like this:

if (shouldLoadOfflinePage) {
    fetchEvent.respondWith(cacheManager.fromCache(new Request(offlinePage)));
} else if (shouldFromCache) {
    fetchEvent.respondWith(cacheManager.fromCache(fetchEvent.request));
} else {
    fetchEvent.respondWith(fetch(fetchEvent.request));
}

The last block intercepts a network-only request which is pretty unnecessary to do. This unnecessary block somehow causes a blocking load (but I don't know what blocks it):

long request to serviceworker wait time: ~400ms

So I decided not to intercept unnecessary fetch-interception (of course by removing the last block):

if (shouldLoadOfflinePage) {
    fetchEvent.respondWith(cacheManager.fromCache(new Request(offlinePage)));
} else if (shouldFromCache) {
    fetchEvent.respondWith(cacheManager.fromCache(fetchEvent.request));
}

Then my page needs only 16ms to load the aforementioned file.

Hope this will help



回答3:

clear out the indexedDB will help to reduce the time it takes to "Request to Service Worker". You could delete it by js:

indexedDB.deleteDatabase(location.host);

or do it manually:

/Users/[USERNAME]/Library/Application Support/Google/Chrome/Default/IndexedDB/