Re: [w3c/ServiceWorker] Service Worker handling of first page load subresources (#1282)

Potential current workaround: Install the SW alone first, then reload the page. The SW then serves content for a SW-enabled page to intercept every request.

See usage at [fetch-progress.anthum.com](https://fetch-progress.anthum.com/sw-basic/) (open in Incognito mode to force SW install)

### index.html
```html
<p>Installing Service Worker, please wait...</p>

<script>
  navigator.serviceWorker.register('sw.js')
  .then(reg => {
    if (reg.installing) {
      const sw = reg.installing || reg.waiting;
      sw.onstatechange = function() {
        if (sw.state === 'installed') {
          // SW installed.  Reload for SW intercept serving SW-enabled page.
          window.location.reload();
        }
      };
    } else if (reg.active) {
      // something's not right or SW is bypassed.  previously-installed SW should have redirected this request to different page
      handleError(new Error('Service Worker is installed and not redirecting.'))
    }
  })
  .catch(handleError)

  function handleError(error) {}
</script>
```

### sw.js
```js
self.addEventListener('fetch', event => {
  const url = event.request.url;
  const scope = self.registration.scope;

  // detect "index.html" or URI ending in "/"
  if (url === scope || url === scope+'index.html') {
    // serve index.html with service-worker-enabled page
    const newUrl = scope+'index-sw-enabled.html';
    event.respondWith(fetch(newUrl))
  } else {
    // process other files here
  }
});
```

### index-sw-enabled.html
_This page loads in browser as URI `index.html` after SW installs. Put intended app/page content here._

-- 
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/1282#issuecomment-619479312

Received on Sunday, 26 April 2020 04:21:41 UTC