How to handle fetch events from the very beginning using a Service Worker?
<p>I'm trying to build a basic service worker to handle all AJAX requests sent from my website.</p>

<p>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.</p>

<p>Once the service worker is installed, if I refresh the web page, then the fetch event handler works.</p>

<p>I want my service worker to fetch all requests from the very beginning. Is it possible?</p>

<p>Here's the code I have:</p>

<p><strong>index.html</strong></p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body&gt;
&lt;h2&gt;Service Worker Demo Page&lt;/h2&gt;
&lt;script type="text/javascript"&gt;

  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);

  }

&lt;/script&gt;

&lt;/body&gt;
</code></pre>

<p><strong>sw.js</strong></p>

<pre><code>self.addEventListener('fetch', function (e) {
  console.info('%s request to %s. More details: %o'
    , e.request.method
    , e.request.url
    , e
  );
});
</code></pre>