title: Making a Simple Site Work Offline with ServiceWorker
url: https://css-tricks.com/serviceworker-for-offline/
hash_url: cafe9b16715f3da507547bbde95f89ac

<p><em class="explanation">When <a href="https://bevacqua.io/">Nicolas Bevacqua</a> (of <a href="https://ponyfoo.com/">Pony Foo</a>) started talking about a potential guest post, I knew right away we should do something with offline. Nicolas has been writing a lot about the ServiceWorker API and offline stuff is one of the things it was made for. Rather than a theoretical look with code snippets, I thought we could combine that with <a href="https://css-tricks.com/examples/Simple-Offline-Site/">a demo website</a> with it all working. So that's what we did - take it away Nicolas!</em></p>
<p><span id="more-210533"/></p>
<p>I’ve been playing around with ServiceWorker a lot recently, so when Chris asked me to write an article about it I couldn’t have been more thrilled. ServiceWorker is the most impactful modern web technology since Ajax. It’s an API that lives inside the browser and sits between your web pages and your application servers. Once installed and activated, a ServiceWorker can programmatically determine how to respond to requests for resources from your origin, even when the browser is offline. ServiceWorker can be used to power the so-called “Offline-First” web.</p>
<p>ServiceWorker is a progressive technology, and in this article I’ll show you how to take a website and make it available offline for humans who are using a modern browser while leaving humans with unsupported browsers unaffected. </p>
<p>Here's a silent, 26 second video of a supporting browser (Chrome) going offline and the final demo site still working:</p>
<p><iframe src="https://www.youtube.com/embed/9WdMKdQHBBE" frameborder="0" allowfullscreen="">VIDEO</iframe></p>
<h3>Browser Support</h3>
<p>Today, ServiceWorker has browser support in Google Chrome, Opera, and in Firefox behind a configuration flag. Microsoft is <a href="https://twitter.com/jacobrossi/status/608291251121618944">likely to work on it</a> soon. There’s no official word from Apple’s Safari yet. </p>
<p>Jake Archibald has a <a href="https://jakearchibald.github.io/isserviceworkerready/">page tracking the support of all the ServiceWorker-related technologies</a>.</p>
<figure id="post-234765" class="align-right media-234765"><img src="https://cdn.css-tricks.com/wp-content/uploads/2015/11/sw-browsers.png" alt=""/></figure>
<p>Given the fact that you can implement this stuff in a progressive enhancement style (doesn't affect unsupported browsers), it's a great opportunity to get ahead of the pack. The ones that are supported are going to greatly appreciate it.</p>
<p>Before getting started, I should point out a couple of things for you to take into account.</p>
<h3>Secure Connections Only</h3>
<p>You should know that there’s a few hard requirements when it comes to ServiceWorker. First and foremost, <strong>your site needs to be served over a secure connection</strong>. If you’re still serving your site over HTTP, it might be a good excuse to implement HTTPS.</p>
<figure id="post-210536" class="align-none media-210536"><img src="https://cdn.css-tricks.com/wp-content/uploads/2015/11/service-worker1.png" alt=""/><br/>
<figcaption>HTTPS is required for ServiceWorker</figcaption>
</figure>
<p>You could use a CDN proxy like CloudFlare to serve traffic securely. Remember to find and fix mixed content warnings as some browsers may warn your customers about your site being unsafe, otherwise.</p>

<p>While the spec for HTTP/2 doesn’t inherently enforce encrypted connections, browsers intend to implement HTTP/2 and similar technologies <em>only</em> over HTTPS. The ServiceWorker specification, on the other hand, <a href="http://www.w3.org/TR/service-workers/#security-considerations">recommends browser implementation over HTTPS</a>. Browsers have also hinted at marking sites served over unencrypted connections as insecure. Search engines penalize unencrypted results.</p>
<p>“HTTPS only” is the browsers way of saying <em>“this is important, you should do this”.</em></p>
<h3>A <code>Promise</code> Based API</h3>
<p>The future of web browser API implementations is <code>Promise</code>-heavy. The <code>fetch</code> API, for example, sprinkles sweet <code>Promise</code>-based sugar on top of <code>XMLHttpRequest</code>. ServiceWorker makes occasional use of <code>fetch</code>, but there’s also worker registration, caching, and message passing, all of which are Promise-based.</p>

<figure id="post-210537" class="align-none media-210537"><img src="https://cdn.css-tricks.com/wp-content/uploads/2015/11/promises.png" alt=""/></figure>
<p>Whether or not you are a fan of promises, they are here to stay, so you better get used to them.</p>
<h3>Registering Your First ServiceWorker</h3>
<p>I worked together with Chris on the simplest possible practical demonstration of how to use ServiceWorker. He implemented a simple website (static HTML, CSS, JavaScript, and images) and asked me to add offline support. I felt like that’d be a great opportunity to display how easy and unobtrusive it is to add offline capabilities to an existing website.</p>
<p>If you’d like to skip to the end, take a look at the <a href="https://github.com/chriscoyier/Simple-Offline-Site/commit/4928bfe074ec39ce72c27bb9078b8ed50672e938">this commit to the demo site</a> on GitHub.</p>
<p>The first step is to register the ServiceWorker. Instead of blindly attempting the registration, we feature-detect that ServiceWorker is available. </p>
<pre rel="JavaScript"><code class="language-javascript">if ('serviceWorker' in navigator) {&#13;
&#13;
}</code></pre>
<p>The following piece of code demonstrates how we would install a ServiceWorker. The JavaScript resource passed to <code>.register</code> will be executed in the context of a ServiceWorker. Note how registration returns a <code>Promise</code> so that you can track whether or not the ServiceWorker registration was successful. I preceded logging statements with <code>CLIENT</code>: to make it visually easier for me to figure out whether a logging statement was coming from a web page or the ServiceWorker script.</p>
<pre rel="JavaScript"><code class="language-javascript">// ServiceWorker is a progressive technology. Ignore unsupported browsers&#13;
if ('serviceWorker' in navigator) {&#13;
  console.log('CLIENT: service worker registration in progress.');&#13;
  navigator.serviceWorker.register('/service-worker.js').then(function() {&#13;
    console.log('CLIENT: service worker registration complete.');&#13;
  }, function() {&#13;
    console.log('CLIENT: service worker registration failure.');&#13;
  });&#13;
} else {&#13;
  console.log('CLIENT: service worker is not supported.');&#13;
}</code></pre>
<p>The endpoint to the <code>service-worker.js</code> file is quite important. If the script were served from, say, <code>/js/service-worker.js</code> then the ServiceWorker would only be able to intercept requests in the <code>/js/</code> context, but it’d be blind to resources like <code>/other</code>. This is typically an issue because you usually scope your JavaScript files in a <code>/js/</code>, <code>/public/</code>, <code>/assets/</code>, or similar “directory”, whereas you’ll want to serve the ServiceWorker script from the domain root in most cases.</p>
<p>That was, in fact, the only necessary change to your web application code, provided that you had already implemented HTTPS. At this point, supporting browsers will issue a request for <code>/service-worker.js</code> and attempt to install the worker.</p>
<p>How should you structure the <code>service-worker.js</code> file, then?</p>
<h3>Putting Together A ServiceWorker</h3>
<p>ServiceWorker is event-driven and <strong>your code should aim to be stateless</strong>. That’s because when a ServiceWorker isn’t being used it’s shut down, losing all state. You have no control over that, so it’s best to avoid any long-term dependence on in-memory state.</p>
<p>Below, I listed the most notable events you’ll have to handle in a ServiceWorker.</p>
<ul>
<li>The <code>install</code> event fires when a ServiceWorker is first fetched. This is your chance to prime the ServiceWorker cache with the fundamental resources that should be available even while users are offline.</li>
<li>The <code>fetch</code> event fires whenever a request originates from your ServiceWorker scope, and you’ll get a chance to intercept the request and respond immediately, without going to the network.</li>
<li>The <code>activate</code> event fires after a successful installation. You can use it to phase out older versions of the worker. We’ll look at a basic example where we deleted stale cache entries.</li>
</ul>
<p>Let’s go over each event and look at examples of how they could be handled.</p>
<h3>Installing Your ServiceWorker</h3>
<p>A version number is useful when updating the worker logic, allowing you to remove outdated cache entries <a href="https://ponyfoo.com/articles/getting-started-with-serviceworker?verify=0b80097456ce81cfcd2ffb5157eb395a#phasing-out-older-serviceworker-versions">during the activation step</a>, as we’ll see a bit later. We’ll use the following version number as a prefix when creating cache stores.</p>
<pre rel="JavaScript"><code class="language-javascript">var version = 'v1::';</code></pre>
<p>You can use <code>addEventListener</code> to register an event handler for the <code>install</code> event. Using <code>event.waitUntil</code> blocks the installation process on the provided <code>p</code> promise. If the promise is rejected because, for instance, one of the resources failed to be downloaded, the service worker won’t be installed. Here, you can leverage the promise returned from opening a cache with <code>caches.open(name)</code> and then mapping that into <code>cache.addAll(resources)</code>, which downloads and stores responses for the provided resources.</p>
<pre rel="JavaScript"><code class="language-javascript">self.addEventListener("install", function(event) {&#13;
  console.log('WORKER: install event in progress.');&#13;
  event.waitUntil(&#13;
    /* The caches built-in is a promise-based API that helps you cache responses,&#13;
       as well as finding and deleting them.&#13;
    */&#13;
    caches&#13;
      /* You can open a cache by name, and this method returns a promise. We use&#13;
         a versioned cache name here so that we can remove old cache entries in&#13;
         one fell swoop later, when phasing out an older service worker.&#13;
      */&#13;
      .open(version + 'fundamentals')&#13;
      .then(function(cache) {&#13;
        /* After the cache is opened, we can fill it with the offline fundamentals.&#13;
           The method below will add all resources we've indicated to the cache,&#13;
           after making HTTP requests for each of them.&#13;
        */&#13;
        return cache.addAll([&#13;
          '/',&#13;
          '/css/global.css',&#13;
          '/js/global.js'&#13;
        ]);&#13;
      })&#13;
      .then(function() {&#13;
        console.log('WORKER: install completed');&#13;
      })&#13;
  );&#13;
});</code></pre>
<p>Once the install step succeeds, the <code>activate</code> event fires. This helps us <a href="#phasing-out-older-serviceworker-versions">phase out an older ServiceWorker</a>, and we’ll look at it later. For now, let’s focus on the <code>fetch</code> event, which is a bit more interesting.</p>
<h3>Intercepting Fetch Requests</h3>
<p>The <code>fetch</code> event fires whenever a page controlled by this service worker requests a resource. This isn’t limited to <code>fetch</code> or even <code>XMLHttpRequest</code>. Instead, it comprehends even the request for the HTML page on first load, as well as JS and CSS resources, fonts, any images, etc. Note also that requests made against other origins will also be caught by the <code>fetch</code> handler of the ServiceWorker. For instance, requests made against <code>i.imgur.com</code> – the CDN for a popular image hosting site – would also be caught by our service worker as long as the request originated on one of the clients (e.g browser tabs) controlled by the worker.</p>
<p>Just like <code>install</code>, we can block the <code>fetch</code> event by passing a promise to <code>event.respondWith(p)</code>, and when the promise fulfills the worker will respond with that instead of the default action of going to the network. We can use <code>caches.match</code> to look for cached responses, and return those responses instead of going to the network.</p>
<p>As described in the comments, here we’re using an “eventually fresh” caching pattern where we return whatever is stored on the cache but always try to fetch a resource again from the network regardless, to keep the cache updated. If the response we served to the user is stale, they’ll get a fresh response the next time they request the resource. If the network request fails, it’ll try to recover by attempting to serve a hardcoded <code>Response</code>.</p>
<pre rel="JavaScript"><code class="language-javascript">self.addEventListener("fetch", function(event) {&#13;
  console.log('WORKER: fetch event in progress.');&#13;
&#13;
  /* We should only cache GET requests, and deal with the rest of method in the&#13;
     client-side, by handling failed POST,PUT,PATCH,etc. requests.&#13;
  */&#13;
  if (event.request.method !== 'GET') {&#13;
    /* If we don't block the event as shown below, then the request will go to&#13;
       the network as usual.&#13;
    */&#13;
    console.log('WORKER: fetch event ignored.', event.request.method, event.request.url);&#13;
    return;&#13;
  }&#13;
  /* Similar to event.waitUntil in that it blocks the fetch event on a promise.&#13;
     Fulfillment result will be used as the response, and rejection will end in a&#13;
     HTTP response indicating failure.&#13;
  */&#13;
  event.respondWith(&#13;
    caches&#13;
      /* This method returns a promise that resolves to a cache entry matching&#13;
         the request. Once the promise is settled, we can then provide a response&#13;
         to the fetch request.&#13;
      */&#13;
      .match(event.request)&#13;
      .then(function(cached) {&#13;
        /* Even if the response is in our cache, we go to the network as well.&#13;
           This pattern is known for producing "eventually fresh" responses,&#13;
           where we return cached responses immediately, and meanwhile pull&#13;
           a network response and store that in the cache.&#13;
           Read more:&#13;
           https://ponyfoo.com/articles/progressive-networking-serviceworker&#13;
        */&#13;
        var networked = fetch(event.request)&#13;
          // We handle the network request with success and failure scenarios.&#13;
          .then(fetchedFromNetwork, unableToResolve)&#13;
          // We should catch errors on the fetchedFromNetwork handler as well.&#13;
          .catch(unableToResolve);&#13;
&#13;
        /* We return the cached response immediately if there is one, and fall&#13;
           back to waiting on the network as usual.&#13;
        */&#13;
        console.log('WORKER: fetch event', cached ? '(cached)' : '(network)', event.request.url);&#13;
        return cached || networked;&#13;
&#13;
        function fetchedFromNetwork(response) {&#13;
          /* We copy the response before replying to the network request.&#13;
             This is the response that will be stored on the ServiceWorker cache.&#13;
          */&#13;
          var cacheCopy = response.clone();&#13;
&#13;
          console.log('WORKER: fetch response from network.', event.request.url);&#13;
&#13;
          caches&#13;
            // We open a cache to store the response for this request.&#13;
            .open(version + 'pages')&#13;
            .then(function add(cache) {&#13;
              /* We store the response for this request. It'll later become&#13;
                 available to caches.match(event.request) calls, when looking&#13;
                 for cached responses.&#13;
              */&#13;
              cache.put(event.request, cacheCopy);&#13;
            })&#13;
            .then(function() {&#13;
              console.log('WORKER: fetch response stored in cache.', event.request.url);&#13;
            });&#13;
&#13;
          // Return the response so that the promise is settled in fulfillment.&#13;
          return response;&#13;
        }&#13;
&#13;
        /* When this method is called, it means we were unable to produce a response&#13;
           from either the cache or the network. This is our opportunity to produce&#13;
           a meaningful response even when all else fails. It's the last chance, so&#13;
           you probably want to display a "Service Unavailable" view or a generic&#13;
           error response.&#13;
        */&#13;
        function unableToResolve () {&#13;
          /* There's a couple of things we can do here.&#13;
             - Test the Accept header and then return one of the `offlineFundamentals`&#13;
               e.g: `return caches.match('/some/cached/image.png')`&#13;
             - You should also consider the origin. It's easier to decide what&#13;
               "unavailable" means for requests against your origins than for requests&#13;
               against a third party, such as an ad provider&#13;
             - Generate a Response programmaticaly, as shown below, and return that&#13;
          */&#13;
&#13;
          console.log('WORKER: fetch request failed in both cache and network.');&#13;
&#13;
          /* Here we're creating a response programmatically. The first parameter is the&#13;
             response body, and the second one defines the options for the response.&#13;
          */&#13;
          return new Response('&lt;h1&gt;Service Unavailable&lt;/h1&gt;', {&#13;
            status: 503,&#13;
            statusText: 'Service Unavailable',&#13;
            headers: new Headers({&#13;
              'Content-Type': 'text/html'&#13;
            })&#13;
          });&#13;
        }&#13;
      })&#13;
  );&#13;
});</code></pre>
<p>There’s several more strategies, some of which I discuss in <a href="https://ponyfoo.com/articles/serviceworker-revolution">an article about ServiceWorker strategies on my blog</a>.</p>
<p>As promised, let’s look at the code you can use to phase out older versions of your ServiceWorker script.</p>
<h3>Phasing Out Older ServiceWorker Versions</h3>
<p>The <code>activate</code> event fires after a service worker has been successfully installed. It is most useful when phasing out an older version of a service worker, as at this point you know that the new worker was installed correctly. In this example, we delete old caches that don’t match the <code>version</code> for the worker we just finished installing.</p>
<pre rel="JavaScript"><code class="language-javascript">self.addEventListener("activate", function(event) {&#13;
  /* Just like with the install event, event.waitUntil blocks activate on a promise.&#13;
     Activation will fail unless the promise is fulfilled.&#13;
  */&#13;
  console.log('WORKER: activate event in progress.');&#13;
&#13;
  event.waitUntil(&#13;
    caches&#13;
      /* This method returns a promise which will resolve to an array of available&#13;
         cache keys.&#13;
      */&#13;
      .keys()&#13;
      .then(function (keys) {&#13;
        // We return a promise that settles when all outdated caches are deleted.&#13;
        return Promise.all(&#13;
          keys&#13;
            .filter(function (key) {&#13;
              // Filter by keys that don't start with the latest version prefix.&#13;
              return !key.startsWith(version);&#13;
            })&#13;
            .map(function (key) {&#13;
              /* Return a promise that's fulfilled&#13;
                 when each outdated cache is deleted.&#13;
              */&#13;
              return caches.delete(key);&#13;
            })&#13;
        );&#13;
      })&#13;
      .then(function() {&#13;
        console.log('WORKER: activate completed.');&#13;
      })&#13;
  );&#13;
});</code></pre>
<hr/>
<p>You should look at <a href="https://github.com/chriscoyier/Simple-Offline-Site">the full code on the GitHub repository</a> and the <a href="https://css-tricks.com/examples/Simple-Offline-Site/">demo site</a>!</p>
