title: Service worker sends two requests
body: <p>I've implemented a service worker which caches all requests for offline usage, this works fine. But everytime I load a page there are two requests hitting my webserver (one from the service worker and one from the browser)!</p>
  
  <p>How can I cache the request and only load the page once?</p>
  
  <p>service-worker.js</p>
  
  <pre><code>self.addEventListener('install', function(event) {
    //load error page which will show if user has no internet
    var errorPage = new Request('/?p=error&amp;offline');
    event.waitUntil(pushToCache(errorPage));
  });
  
  //If any fetch fails, it will look for the request in the cache and serve it from there first
  self.addEventListener('fetch', function(event) {
    event.waitUntil(pushToCache(event.request));
  
    event.respondWith(
      fetch(event.request) //try loading from internet
      .catch(function (error) {
        return fetchFromCache(event.request);
      }) //no internet connection try getting it from cache
    );
  });
  
  function pushToCache(request){
    if(request.method == "GET"){
      return caches.open('stm-app').then(function (cache) {
        return fetch(request).then(function (response) {
          return cache.put(request, response);
        });
      });
    }
  };
  
  function fetchFromCache(request) {
    return caches.open('stm-app').then(function (cache) {
      return cache.match(request).then(function (matching) {
        if(!matching || matching.status == 404){
          return fetchFromCache(new Request('/?p=error&amp;offline')); //show page that user is offline
        }else{
          return matching;
        }
      });
    });
  }
  </code></pre>
  
  <p>sw-register.js</p>
  
  <pre><code>if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('service-worker.js')
    .then(function(registration) {
      console.log('Registered:', registration);
    })
    .catch(function(error) {
      console.log('Registration failed: ', error);
    });
  }
  </code></pre>