Long time waiting Request to Service Worker

南楼画角 提交于 2019-12-08 16:04:54

问题


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/



来源:https://stackoverflow.com/questions/44106334/long-time-waiting-request-to-service-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!