javascriptservice-workerservice-worker-events

Service-worker not intercepting first fetch call on initial load


I'm having an issue with my custom service-worker. It doesn't seem to be intercepting the first fetch req when the page is initially loaded (but all fetch reqs afterwards are intercepted correctly). However, if I reload the page, all fetch reqs are intercepted correctly by the service-worker. So the problem only exists on initial load of the page.


Solution

  • This "first-load" behavior is by design. ServiceWorkers can't intercept the initial requests until they enter the installing state and end with the activated state. One option is to first show users an "Installing..." page, wait for the SW to become active, and then refresh the page. The SW can then serve an "SW activated" page. See example: https://fetch-progress.anthum.com/sw-basic/ - sw-simple.js

    // INTERCEPT:  /, /index.html, /index.htm 
    if ([scope, scope + 'index.html', scope + 'index.htm'].includes(event.request.url)) {
      event.respondWith(fetch(scope + 'sw-installed.html'))
    }