|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467 |
- title: My first Service Worker
- url: https://adactio.com/journal/9775
- hash_url: c730e6d1352203b60f954d9850a0dfce
-
- <p>I’ve made no secret of the fact that I’m <em>really</em> excited about <a href="http://www.html5rocks.com/en/tutorials/service-worker/introduction/">Service Workers</a>. I’m not alone. At <a href="https://coldfrontconf.com/">the Coldfront conference</a> in Copenhagen, <a href="https://adactio.com/journal/9480">pretty much every talk mentioned Service Workers</a>.</p>
-
- <p>Obviously I’m excited about what Service Workers enable: offline caching, background processes, push notifications, and all sorts of other goodies that allow the web to compete with native. But more than that, I’m really excited about the way that the Service Worker spec has been designed. Instead of being an all-or-nothing technology that you have to bet the farm on, it has been deliberately crafted to be used as an <em>enhancement</em> on top of existing sites (oh, how I wish that web components would follow a similar path).</p>
-
- <p>I’ve got plenty of ideas on how Service Workers could be used to enhance a community site like <a href="https://thesession.org/">The Session</a> or the kind of <a href="http://2015.dconstruct.org/">events sites</a> that we produce at <a href="http://clearleft.com/">Clearleft</a>, but to begin with, I figured it would make sense to use my own personal site as a playground.</p>
-
- <p>To start with, I’ve already conquered the first hurdle: <a href="https://adactio.com/articles/7435">serving my site over HTTPS</a>. Service Workers require a secure connection. But you can play around with running a Service Worker locally if you run a copy of your site on <code>localhost</code>.</p>
-
- <p>That’s how I started experimenting with Service Workers: serving on <code>localhost</code>, and stopping and starting my local Apache server with <code>apachectl stop</code> and <code>apachectl start</code> on the command line.</p>
-
- <p>That reminds of another interesting use case for Service Workers: it’s not just about the user’s network connection failing (say, going into a train tunnel); it’s also about your web server not always being available. Both scenarios are covered equally.</p>
-
- <p>I would never have even attempted to start if it weren’t for the existing examples from people who have been generous enough to share their work:</p>
-
-
-
- <p>Also, I knew that Jake was coming to <a href="http://2015.ffconf.org/">FF Conf</a> so if I got stumped, I could pester him. That’s <a href="https://adactio.com/notes/9769">exactly what ended up happening</a> (thanks, Jake!).</p>
-
- <p>So if you decide to play around with Service Workers, please, please share your experience.</p>
-
- <p>It’s entirely up to you <em>how</em> you use Service Workers. I figured for a personal site like this, it would be nice to:</p>
-
- <ol>
- <li>Explicitly cache resources like CSS, JavaScript, and some images.</li>
- <li>Cache the homepage so it can be displayed even when the network connection fails.</li>
- <li>For other pages, have a fallback “offline” page to display when the network connection fails.</li>
- </ol>
-
- <p>So now I’ve got <a href="https://adactio.com/serviceworker.js">a Service Worker up and running on adactio.com</a>. It will only work in Chrome, Android, Opera, and the forthcoming version of Firefox …and that’s just fine. It’s an enhancement. As more and more browsers start supporting it, this Service Worker will become more and more useful.</p>
-
- <p>How very <a href="http://futurefriendlyweb.com/">future friendly</a>!</p>
-
- <h2>The code</h2>
-
- <p>If you’re interested in the nitty-gritty of what <a href="https://adactio.com/serviceworker.js">my Service Worker</a> is doing, read on. If, on the other hand, code is not your bag, now would be a good time to bow out.</p>
-
- <p>If you want to jump straight to the finished code, <a href="https://gist.github.com/adactio/fbaa3a5952774553f5e7">here’s a gist</a>. Feel free to take it, break it, copy it, improve it, or do anything else you want with it.</p>
-
- <p>To start with, let’s establish exactly what a Service Worker is. I like <a href="http://www.html5rocks.com/en/tutorials/service-worker/introduction/">this definition by Matt Gaunt</a>:</p>
-
- <blockquote>
- <p>A service worker is a script that is run by your browser in the background, separate from a web page, opening the door to features which don’t need a web page or user interaction.</p>
- </blockquote>
-
- <h3><code>register</code></h3>
-
- <p>From inside <a href="https://adactio.com/includes/javascript/global.js">my site’s global JavaScript file</a>—or I could do this from a script element inside my pages—I’m going to do a quick bit of feature detection for Service Workers. If the browser supports it, then I’m going register my Service Worker by pointing to another JavaScript file, which sits at the root of my site:</p>
-
- <pre><code>if (navigator.serviceWorker) {
- navigator.serviceWorker.register('/serviceworker.js', {
- scope: '/'
- });
- }
- </code></pre>
-
- <p>The <code>serviceworker.js</code> file sits in the root of my site so that it can act on any requests to my domain. If I put it somewhere like <code>/js/serviceworker.js</code>, then it would only be able to act on requests to the <code>/js</code> directory.</p>
-
- <p>Once that file has been loaded, the installation of the Service Worker can begin. That means the script will be installed in the user’s browser …and it will live there even after the user has left my website.</p>
-
- <h3><code>install</code></h3>
-
- <p>I’m making the installation of the Service Worker dependent on a function called <code>updateStaticCache</code> that will populate a cache with the files I want to store:</p>
-
- <pre><code>self.addEventListener('install', function (event) {
- event.waitUntil(updateStaticCache());
- });
- </code></pre>
-
- <p>That <code>updateStaticCache</code> function will be used for storing items in a cache. I’m going to make sure that the cache has a version number in its name, exactly <a href="https://www.theguardian.com/info/developer-blog/2015/nov/04/building-an-offline-page-for-theguardiancom">as described in the Guardian’s use case</a>. That way, when I want to update the cache, I only need to update the version number.</p>
-
- <pre><code>var staticCacheName = 'static';
- var version = 'v1::';
- </code></pre>
-
- <p>Here’s the <code>updateStaticCache</code> function that puts the items I want into the cache. I’m storing my JavaScript, my CSS, some images referenced in the CSS, the home page of my site, and a page for displaying when offline.</p>
-
- <pre><code>function updateStaticCache() {
- return caches.open(version + staticCacheName)
- .then(function (cache) {
- return cache.addAll([
- '/path/to/javascript.js',
- '/path/to/stylesheet.css',
- '/path/to/someimage.png',
- '/path/to/someotherimage.png',
- '/',
- '/offline'
- ]);
- });
- };
- </code></pre>
-
- <p>Because those items are part of the <code>return</code> statement for the Promise created by <code>caches.open</code>, the Service Worker won’t install until all of those items are in the cache. So you might want to keep them to a minimum.</p>
-
- <p>You can still put other items in the cache, and not make them part of the return statement. That way, they’ll get added to the cache in their own good time, and the installation of the Service Worker won’t be delayed:</p>
-
- <pre><code>function updateStaticCache() {
- return caches.open(version + staticCacheName)
- .then(function (cache) {
- cache.addAll([
- '/path/to/somefile',
- '/path/to/someotherfile'
- ]);
- return cache.addAll([
- '/path/to/javascript.js',
- '/path/to/stylesheet.css',
- '/path/to/someimage.png',
- '/path/to/someotherimage.png',
- '/',
- '/offline'
- ]);
- });
- }
- </code></pre>
-
- <p>Another option is to use completely different caches, but I’ve decided to just use one cache for now.</p>
-
- <h3><code>activate</code></h3>
-
- <p>When the <code>activate</code> event fires, it’s a good opportunity to clean up any caches that are out of date (by looking for anything that doesn’t match the current version number). I copied this <a href="https://ponyfoo.com/articles/serviceworker-revolution">straight from Nicolas’s code</a>:</p>
-
- <pre><code>self.addEventListener('activate', function (event) {
- event.waitUntil(
- caches.keys()
- .then(function (keys) {
- return Promise.all(keys
- .filter(function (key) {
- return key.indexOf(version) !== 0;
- })
- .map(function (key) {
- return caches.delete(key);
- })
- );
- })
- );
- });
- </code></pre>
-
- <h3><code>fetch</code></h3>
-
- <p>The <code>fetch</code> event is fired every time the browser is going to request a file from my site. The magic of Service Worker is that I can intercept that request before it happens and decide what to do with it:</p>
-
- <pre><code>self.addEventListener('fetch', function (event) {
- var request = event.request;
- ...
- });
- </code></pre>
-
- <h4>POST requests</h4>
-
- <p>For a start, I’m going to just back off from any requests that aren’t GET requests:</p>
-
- <pre><code>if (request.method !== 'GET') {
- event.respondWith(
- fetch(request)
- );
- return;
- }
- </code></pre>
-
- <p>That’s basically just replicating what the browser would do anyway. But even here I could decide to fall back to <a href="https://adactio.com/offline">my offline page</a> if the request doesn’t succeed. I do that using a <code>catch</code> clause appended to the <code>fetch</code> statement:</p>
-
- <pre><code>if (request.method !== 'GET') {
- event.respondWith(
- fetch(request)
- .catch(function () {
- return caches.match('/offline');
- })
- );
- return;
- }
- </code></pre>
-
- <h4>HTML requests</h4>
-
- <p>I’m going to treat requests for pages differently to requests for files. If the browser is requesting a page, then here’s the order I want:</p>
-
- <ol>
- <li>Try fetching the page from the network first.</li>
- <li>If that doesn’t work, try looking for the page in the cache.</li>
- <li>If all else fails, show <a href="https://adactio.com/offline">the offline page</a>.</li>
- </ol>
-
- <p>First of all, I need to test to see if the request is for an HTML document. I’m doing this by sniffing the Accept headers, which probably isn’t the safest method:</p>
-
- <pre><code>if (request.headers.get('Accept').indexOf('text/html') !== -1) {
- </code></pre>
-
- <p>Now I try to fetch the page from the network:</p>
-
- <pre><code>event.respondWith(
- fetch(request)
- );
- </code></pre>
-
- <p>If the network is working fine, this will return the response from the site and I’ll pass that along.</p>
-
- <p>But if that doesn’t work, I’m going to look for a match in the cache. Time for a <code>catch</code> clause:</p>
-
- <pre><code>.catch(function () {
- return caches.match(request);
- })
- </code></pre>
-
- <p>So now the whole event.respondWith statement looks like this:</p>
-
- <pre><code>event.respondWith(
- fetch(request)
- .catch(function () {
- return caches.match(request)
- })
- );
- </code></pre>
-
- <p>Finally, I need to take care of the situation when the page can’t be fetched from the network <em>and</em> it can’t be found in the cache.</p>
-
- <p>Now, I first tried to do this by adding a <code>catch</code> clause to the <code>caches.match</code> statement, like this:</p>
-
- <pre><code>return caches.match(request)
- .catch(function () {
- return caches.match('/offline');
- })
- </code></pre>
-
- <p>That didn’t work and for the life of me, I couldn’t figure out why. Then <a href="https://jakearchibald.com">Jake</a> set me straight. It turns out that <code>caches.match</code> will <em>always</em> return a response …even if that response is <code>undefined</code>. So a <code>catch</code> clause will never be triggered. Instead I need to return the offline page if the response from the cache is falsey:</p>
-
- <pre><code>return caches.match(request)
- .then(function (response) {
- return response || caches.match('/offline');
- })
- </code></pre>
-
- <p>With that cleared up, my code for handing HTML requests looks like this:</p>
-
- <pre><code>event.respondWith(
- fetch(request, { credentials: 'include' })
- .catch(function () {
- return caches.match(request)
- .then(function (response) {
- return response || caches.match('/offline');
- })
- })
- );
- </code></pre>
-
- <p>Actually, there’s one more thing I’m doing with HTML requests. If the network request succeeds, I stash the response in the cache.</p>
-
- <p>Well, that’s not <em>exactly</em> true. I stash a <strong>copy</strong> of the response in the cache. That’s because you’re only allowed to read the value of a response once. So if I want to do anything with it, I have to clone it:</p>
-
- <pre><code>var copy = response.clone();
- caches.open(version + staticCacheName)
- .then(function (cache) {
- cache.put(request, copy);
- });
- </code></pre>
-
- <p>I do that right before returning the actual response. Here’s how it fits together:</p>
-
- <pre><code>if (request.headers.get('Accept').indexOf('text/html') !== -1) {
- event.respondWith(
- fetch(request, { credentials: 'include' })
- .then(function (response) {
- var copy = response.clone();
- caches.open(version + staticCacheName)
- .then(function (cache) {
- cache.put(request, copy);
- });
- return response;
- })
- .catch(function () {
- return caches.match(request)
- .then(function (response) {
- return response || caches.match('/offline');
- })
- })
- );
- return;
- }
- </code></pre>
-
- <p>Okay. So that’s requests for pages taken care of.</p>
-
- <h4>File requests</h4>
-
- <p>I want to handle requests for files differently to requests for pages. Here’s my list of priorities:</p>
-
- <ol>
- <li>Look for the file in the cache first.</li>
- <li>If that doesn’t work, make a network request.</li>
- <li>If all else fails, and it’s a request for an image, show a placeholder.</li>
- </ol>
-
- <p>Step one: try getting the file from the cache:</p>
-
- <pre><code>event.respondWith(
- caches.match(request)
- );
- </code></pre>
-
- <p>Step two: if that didn’t work, go out to the network. Now remember, I can’t use a <code>catch</code> clause here, because <code>caches.match</code> will always return something: either a response or <code>undefined</code>. So here’s what I do:</p>
-
- <pre><code>event.respondWith(
- caches.match(request)
- .then(function (response) {
- return response || fetch(request);
- })
- );
- </code></pre>
-
- <p>Now that I’m back to dealing with a <code>fetch</code> statement, I <em>can</em> use a <code>catch</code> clause to take care of the third and final step: if the network request doesn’t succeed, check to see if the request was for an image, and if so, display a placeholder:</p>
-
- <pre><code>.catch(function () {
- if (request.headers.get('Accept').indexOf('image') !== -1) {
- return new Response('<svg>...</svg>', { headers: { 'Content-Type': 'image/svg+xml' }});
- }
- })
- </code></pre>
-
- <p>I could point to a placeholder image in the cache, but I’ve decided to send an SVG on the fly using a new <code>Response</code> object.</p>
-
- <p>Here’s how the whole thing looks:</p>
-
- <pre><code>event.respondWith(
- caches.match(request)
- .then(function (response) {
- return response || fetch(request)
- .catch(function () {
- if (request.headers.get('Accept').indexOf('image') !== -1) {
- return new Response('<svg>...</svg>', { headers: { 'Content-Type': 'image/svg+xml' }});
- }
- })
- })
- );
- </code></pre>
-
- <p>The overall shape of my code to handle <code>fetch</code> events now looks like this:</p>
-
- <pre><code>self.addEventListener('fetch', function (event) {
- var request = event.request;
- // Non-GET requests
- if (request.method !== 'GET') {
- event.respondWith(
- ...
- );
- return;
- }
- // HTML requests
- if (request.headers.get('Accept').indexOf('text/html') !== -1) {
- event.respondWith(
- ...
- );
- return;
- }
- // Non-HTML requests
- event.respondWith(
- ...
- );
- });
- </code></pre>
-
- <p>Feel free to <a href="https://gist.github.com/adactio/fbaa3a5952774553f5e7">peruse the code</a>.</p>
-
- <h3>Next steps</h3>
-
- <p>The code I’m running now is fine for a first stab, but there’s room for improvement.</p>
-
- <p>Right now I’m stashing any HTML pages the user visits into the cache. I don’t <em>think</em> that will get out of control—I imagine most people only ever visit just a handful of pages on my site. But there’s the chance that the cache could get quite bloated. Ideally I’d have some way of keeping the cache nice and lean.</p>
-
- <p>I was thinking: maybe I should have a separate cache for HTML pages, and limit the number in that cache to, say, 20 or 30 items. Every time I push something new into that cache, I could pop the oldest item out.</p>
-
- <p>I could imagine doing something similar for images: keeping a cache of just the most recent 10 or 20.</p>
-
- <p>If you fancy having a go at coding that up, let me know.</p>
-
- <h3>Lessons learned</h3>
-
- <p>There were a few gotchas along the way. I already mentioned the fact that <code>caches.match</code> will always return something so you can’t use <code>catch</code> clauses to handle situations where a file isn’t found in the cache.</p>
-
- <p>Something else worth noting is that this:</p>
-
- <pre><code>fetch(request);
- </code></pre>
-
- <p>…is functionally equivalent to this:</p>
-
- <pre><code>fetch(request)
- .then(function (response) {
- return response;
- });
- </code></pre>
-
- <p>That’s probably obvious but it took me a while to realise. Likewise:</p>
-
- <pre><code>caches.match(request);
- </code></pre>
-
- <p>…is the same as:</p>
-
- <pre><code>caches.match(request)
- .then(function (response) {
- return response;
- });
- </code></pre>
-
- <p>Here’s another thing… you’ll notice that sometimes I’ve used:</p>
-
- <pre><code>fetch(request);
- </code></pre>
-
- <p>…but sometimes I’ve used:</p>
-
- <pre><code>fetch(request, { credentials: 'include' } );
- </code></pre>
-
- <p>That’s because, by default, a <code>fetch</code> request doesn’t include cookies. That’s fine if the request is for a static file, but if it’s for a potentially-dynamic HTML page, you probably want to make sure that the Service Worker request is no different from a regular browser request. You can do that by passing through that second (optional) argument.</p>
-
- <p>But probably the trickiest thing is getting your head around the idea of <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Promises</a>. Writing JavaScript is generally a fairly procedural affair, but once you start dealing with <code>then</code> clauses, you have to come to grips with the fact that the contents of those clauses will return asynchronously. So statements written <em>after</em> the <code>then</code> clause will probably execute <em>before</em> the code inside the clause. It’s kind of hard to explain, but if you find problems with your Service Worker code, check to see if that’s the cause.</p>
-
- <p>And remember, please share <em>your</em> code and <em>your</em> gotchas: it’s early days for Service Workers so every implementation counts.</p>
-
- <h4>Updates</h4>
-
- <p>I got some very useful feedback from Jake after I published this…</p>
-
- <h5>Expires headers</h5>
-
- <p>By default, JavaScript files on my server are cached for a month. But a Service Worker script probably shouldn’t be cached at all (or cached for a very, very short time). I’ve updated my <code>.htaccess</code> rules accordingly:</p>
-
- <pre><code><FilesMatch "serviceworker.js">
- ExpiresDefault "now"
- </FilesMatch>
- </code></pre>
-
- <h5>Credentials</h5>
-
- <p>If a request is initiated by the browser, I don’t need to say:</p>
-
- <pre><code>fetch(request, { credentials: 'include' } );
- </code></pre>
-
- <p>It’s enough to just say:</p>
-
- <pre><code>fetch(request);
- </code></pre>
-
- <h5>Scope</h5>
-
- <p>I set the <code>scope</code> parameter of my Service Worker to be “/” …but because the Service Worker is sitting in the root directory anyway, I don’t really need to do that. I could just register it with:</p>
-
- <pre><code>if (navigator.serviceWorker) {
- navigator.serviceWorker.register('/serviceworker.js');
- }
- </code></pre>
-
- <p>If, on the other hand, the Service Worker file were sitting in a folder, but I wanted it to act on the whole site, <em>then</em> I would need to specify the scope:</p>
-
- <pre><code>if (navigator.serviceWorker) {
- navigator.serviceWorker.register('/path/to/serviceworker.js', {
- scope: '/'
- });
- }
- </code></pre>
-
- <p>…and I’d also need to <a href="https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-script-response">send a special header</a>. So it’s probably easiest to just put Service Worker scripts in the root directory.</p>
|