A place to cache linked articles (think custom and personal wayback machine)
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

vor 5 Jahren
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. title: My first Service Worker
  2. url: https://adactio.com/journal/9775
  3. hash_url: c730e6d1352203b60f954d9850a0dfce
  4. <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>
  5. <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>
  6. <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>
  7. <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>
  8. <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>
  9. <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>
  10. <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>
  11. <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>
  12. <p>So if you decide to play around with Service Workers, please, please share your experience.</p>
  13. <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>
  14. <ol>
  15. <li>Explicitly cache resources like CSS, JavaScript, and some images.</li>
  16. <li>Cache the homepage so it can be displayed even when the network connection fails.</li>
  17. <li>For other pages, have a fallback “offline” page to display when the network connection fails.</li>
  18. </ol>
  19. <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>
  20. <p>How very <a href="http://futurefriendlyweb.com/">future friendly</a>!</p>
  21. <h2>The code</h2>
  22. <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>
  23. <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>
  24. <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>
  25. <blockquote>
  26. <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>
  27. </blockquote>
  28. <h3><code>register</code></h3>
  29. <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>
  30. <pre><code>if (navigator.serviceWorker) {
  31. navigator.serviceWorker.register('/serviceworker.js', {
  32. scope: '/'
  33. });
  34. }
  35. </code></pre>
  36. <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>
  37. <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>
  38. <h3><code>install</code></h3>
  39. <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>
  40. <pre><code>self.addEventListener('install', function (event) {
  41. event.waitUntil(updateStaticCache());
  42. });
  43. </code></pre>
  44. <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>
  45. <pre><code>var staticCacheName = 'static';
  46. var version = 'v1::';
  47. </code></pre>
  48. <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>
  49. <pre><code>function updateStaticCache() {
  50. return caches.open(version + staticCacheName)
  51. .then(function (cache) {
  52. return cache.addAll([
  53. '/path/to/javascript.js',
  54. '/path/to/stylesheet.css',
  55. '/path/to/someimage.png',
  56. '/path/to/someotherimage.png',
  57. '/',
  58. '/offline'
  59. ]);
  60. });
  61. };
  62. </code></pre>
  63. <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>
  64. <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>
  65. <pre><code>function updateStaticCache() {
  66. return caches.open(version + staticCacheName)
  67. .then(function (cache) {
  68. cache.addAll([
  69. '/path/to/somefile',
  70. '/path/to/someotherfile'
  71. ]);
  72. return cache.addAll([
  73. '/path/to/javascript.js',
  74. '/path/to/stylesheet.css',
  75. '/path/to/someimage.png',
  76. '/path/to/someotherimage.png',
  77. '/',
  78. '/offline'
  79. ]);
  80. });
  81. }
  82. </code></pre>
  83. <p>Another option is to use completely different caches, but I’ve decided to just use one cache for now.</p>
  84. <h3><code>activate</code></h3>
  85. <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>
  86. <pre><code>self.addEventListener('activate', function (event) {
  87. event.waitUntil(
  88. caches.keys()
  89. .then(function (keys) {
  90. return Promise.all(keys
  91. .filter(function (key) {
  92. return key.indexOf(version) !== 0;
  93. })
  94. .map(function (key) {
  95. return caches.delete(key);
  96. })
  97. );
  98. })
  99. );
  100. });
  101. </code></pre>
  102. <h3><code>fetch</code></h3>
  103. <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>
  104. <pre><code>self.addEventListener('fetch', function (event) {
  105. var request = event.request;
  106. ...
  107. });
  108. </code></pre>
  109. <h4>POST requests</h4>
  110. <p>For a start, I’m going to just back off from any requests that aren’t GET requests:</p>
  111. <pre><code>if (request.method !== 'GET') {
  112. event.respondWith(
  113. fetch(request)
  114. );
  115. return;
  116. }
  117. </code></pre>
  118. <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>
  119. <pre><code>if (request.method !== 'GET') {
  120. event.respondWith(
  121. fetch(request)
  122. .catch(function () {
  123. return caches.match('/offline');
  124. })
  125. );
  126. return;
  127. }
  128. </code></pre>
  129. <h4>HTML requests</h4>
  130. <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>
  131. <ol>
  132. <li>Try fetching the page from the network first.</li>
  133. <li>If that doesn’t work, try looking for the page in the cache.</li>
  134. <li>If all else fails, show <a href="https://adactio.com/offline">the offline page</a>.</li>
  135. </ol>
  136. <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>
  137. <pre><code>if (request.headers.get('Accept').indexOf('text/html') !== -1) {
  138. </code></pre>
  139. <p>Now I try to fetch the page from the network:</p>
  140. <pre><code>event.respondWith(
  141. fetch(request)
  142. );
  143. </code></pre>
  144. <p>If the network is working fine, this will return the response from the site and I’ll pass that along.</p>
  145. <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>
  146. <pre><code>.catch(function () {
  147. return caches.match(request);
  148. })
  149. </code></pre>
  150. <p>So now the whole event.respondWith statement looks like this:</p>
  151. <pre><code>event.respondWith(
  152. fetch(request)
  153. .catch(function () {
  154. return caches.match(request)
  155. })
  156. );
  157. </code></pre>
  158. <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>
  159. <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>
  160. <pre><code>return caches.match(request)
  161. .catch(function () {
  162. return caches.match('/offline');
  163. })
  164. </code></pre>
  165. <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>
  166. <pre><code>return caches.match(request)
  167. .then(function (response) {
  168. return response || caches.match('/offline');
  169. })
  170. </code></pre>
  171. <p>With that cleared up, my code for handing HTML requests looks like this:</p>
  172. <pre><code>event.respondWith(
  173. fetch(request, { credentials: 'include' })
  174. .catch(function () {
  175. return caches.match(request)
  176. .then(function (response) {
  177. return response || caches.match('/offline');
  178. })
  179. })
  180. );
  181. </code></pre>
  182. <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>
  183. <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>
  184. <pre><code>var copy = response.clone();
  185. caches.open(version + staticCacheName)
  186. .then(function (cache) {
  187. cache.put(request, copy);
  188. });
  189. </code></pre>
  190. <p>I do that right before returning the actual response. Here’s how it fits together:</p>
  191. <pre><code>if (request.headers.get('Accept').indexOf('text/html') !== -1) {
  192. event.respondWith(
  193. fetch(request, { credentials: 'include' })
  194. .then(function (response) {
  195. var copy = response.clone();
  196. caches.open(version + staticCacheName)
  197. .then(function (cache) {
  198. cache.put(request, copy);
  199. });
  200. return response;
  201. })
  202. .catch(function () {
  203. return caches.match(request)
  204. .then(function (response) {
  205. return response || caches.match('/offline');
  206. })
  207. })
  208. );
  209. return;
  210. }
  211. </code></pre>
  212. <p>Okay. So that’s requests for pages taken care of.</p>
  213. <h4>File requests</h4>
  214. <p>I want to handle requests for files differently to requests for pages. Here’s my list of priorities:</p>
  215. <ol>
  216. <li>Look for the file in the cache first.</li>
  217. <li>If that doesn’t work, make a network request.</li>
  218. <li>If all else fails, and it’s a request for an image, show a placeholder.</li>
  219. </ol>
  220. <p>Step one: try getting the file from the cache:</p>
  221. <pre><code>event.respondWith(
  222. caches.match(request)
  223. );
  224. </code></pre>
  225. <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>
  226. <pre><code>event.respondWith(
  227. caches.match(request)
  228. .then(function (response) {
  229. return response || fetch(request);
  230. })
  231. );
  232. </code></pre>
  233. <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>
  234. <pre><code>.catch(function () {
  235. if (request.headers.get('Accept').indexOf('image') !== -1) {
  236. return new Response('&lt;svg&gt;...&lt;/svg&gt;', { headers: { 'Content-Type': 'image/svg+xml' }});
  237. }
  238. })
  239. </code></pre>
  240. <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>
  241. <p>Here’s how the whole thing looks:</p>
  242. <pre><code>event.respondWith(
  243. caches.match(request)
  244. .then(function (response) {
  245. return response || fetch(request)
  246. .catch(function () {
  247. if (request.headers.get('Accept').indexOf('image') !== -1) {
  248. return new Response('&lt;svg&gt;...&lt;/svg&gt;', { headers: { 'Content-Type': 'image/svg+xml' }});
  249. }
  250. })
  251. })
  252. );
  253. </code></pre>
  254. <p>The overall shape of my code to handle <code>fetch</code> events now looks like this:</p>
  255. <pre><code>self.addEventListener('fetch', function (event) {
  256. var request = event.request;
  257. // Non-GET requests
  258. if (request.method !== 'GET') {
  259. event.respondWith(
  260. ...
  261. );
  262. return;
  263. }
  264. // HTML requests
  265. if (request.headers.get('Accept').indexOf('text/html') !== -1) {
  266. event.respondWith(
  267. ...
  268. );
  269. return;
  270. }
  271. // Non-HTML requests
  272. event.respondWith(
  273. ...
  274. );
  275. });
  276. </code></pre>
  277. <p>Feel free to <a href="https://gist.github.com/adactio/fbaa3a5952774553f5e7">peruse the code</a>.</p>
  278. <h3>Next steps</h3>
  279. <p>The code I’m running now is fine for a first stab, but there’s room for improvement.</p>
  280. <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>
  281. <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>
  282. <p>I could imagine doing something similar for images: keeping a cache of just the most recent 10 or 20.</p>
  283. <p>If you fancy having a go at coding that up, let me know.</p>
  284. <h3>Lessons learned</h3>
  285. <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>
  286. <p>Something else worth noting is that this:</p>
  287. <pre><code>fetch(request);
  288. </code></pre>
  289. <p>…is functionally equivalent to this:</p>
  290. <pre><code>fetch(request)
  291. .then(function (response) {
  292. return response;
  293. });
  294. </code></pre>
  295. <p>That’s probably obvious but it took me a while to realise. Likewise:</p>
  296. <pre><code>caches.match(request);
  297. </code></pre>
  298. <p>…is the same as:</p>
  299. <pre><code>caches.match(request)
  300. .then(function (response) {
  301. return response;
  302. });
  303. </code></pre>
  304. <p>Here’s another thing… you’ll notice that sometimes I’ve used:</p>
  305. <pre><code>fetch(request);
  306. </code></pre>
  307. <p>…but sometimes I’ve used:</p>
  308. <pre><code>fetch(request, { credentials: 'include' } );
  309. </code></pre>
  310. <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>
  311. <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>
  312. <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>
  313. <h4>Updates</h4>
  314. <p>I got some very useful feedback from Jake after I published this…</p>
  315. <h5>Expires headers</h5>
  316. <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>
  317. <pre><code>&lt;FilesMatch "serviceworker.js"&gt;
  318. ExpiresDefault "now"
  319. &lt;/FilesMatch&gt;
  320. </code></pre>
  321. <h5>Credentials</h5>
  322. <p>If a request is initiated by the browser, I don’t need to say:</p>
  323. <pre><code>fetch(request, { credentials: 'include' } );
  324. </code></pre>
  325. <p>It’s enough to just say:</p>
  326. <pre><code>fetch(request);
  327. </code></pre>
  328. <h5>Scope</h5>
  329. <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>
  330. <pre><code>if (navigator.serviceWorker) {
  331. navigator.serviceWorker.register('/serviceworker.js');
  332. }
  333. </code></pre>
  334. <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>
  335. <pre><code>if (navigator.serviceWorker) {
  336. navigator.serviceWorker.register('/path/to/serviceworker.js', {
  337. scope: '/'
  338. });
  339. }
  340. </code></pre>
  341. <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>