I'm trying to build a basic service worker to handle all AJAX requests sent from my website.
Service worker is subscribed to the fetch event. I can handle all request sent but it doesn't work the first time the service worker is installed.
Once the service worker is installed, if I refresh the web page, then the fetch event handler works.
I want my service worker to fetch all requests from the very beginning. Is it possible?
Here's the code I have:
index.html
<!DOCTYPE html>
<html>
<body>
<h2>Service Worker Demo Page</h2>
<script type="text/javascript">
if (navigator.serviceWorker) {
navigator.serviceWorker.register('./sw.js')
.then(function (registration) {
console.debug('Registration within scope %s. More details %O', registration.scope, registration);
return fetch('https://www.google.com');
})
.then(console.info)
.catch(console.warn);
}
</script>
</body>
sw.js
self.addEventListener('fetch', function (e) {
console.info('%s request to %s. More details: %o'
, e.request.method
, e.request.url
, e
);
});
The default behaviour of is that a webpage must be refreshed before its service worker becomes active. So, the "very beginning" for you (the user) is not the same "very beginning" of the service worker.
However, you can override this default behaviour by using
clients.claim(). Read about it on MDN:Note that for your use case you should ensure that the SW is registered and activated before firing any fetch events.
______
Read more about the service worker lifecycle in the "Service Worker Lifecycle" blog post. Here are some relevant bullet points...