A place to cache linked articles (think custom and personal wayback machine)
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.md 22KB

4 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. title: Introduction to Service Worker
  2. url: http://www.html5rocks.com/en/tutorials/service-worker/introduction/
  3. hash_url: 64fd51915364724e3489270d05a68907
  4. <p>Rich offline experiences, periodic background syncs, push notifications—
  5. functionality that would normally require a native application—are coming to
  6. the web. Service workers provide the technical foundation that all these
  7. features will rely on.</p>
  8. <h2 id="toc-what">What is a Service Worker?</h2>
  9. <p>A service worker is a script that is run by your browser in the background,
  10. separate from a web page, opening the door to features which don't need a web
  11. page or user interaction. Today, they already include features like
  12. <a href="http://updates.html5rocks.com/2015/03/push-notificatons-on-the-open-web">
  13. push notifications</a> and in the future it will include other things like,
  14. background sync, or geofencing. The core feature discussed in this tutorial is
  15. the ability to intercept and handle network requests, including programmatically
  16. managing a cache of responses.</p>
  17. <p>The reason this is such an exciting API is that it allows you to support offline
  18. experiences, giving developers complete control over what exactly that
  19. experience is.</p>
  20. <p>Before service worker there was one other API that would give users an offline
  21. experience on the web called <a href="/tutorials/appcache/beginner/">App
  22. Cache</a>. The major
  23. issue with App Cache is the <a href="http://alistapart.com/article/application-cache-is-a-douchebag">number
  24. of gotcha's that exist</a> as well
  25. as the design working particularly well for single page web apps, but not for
  26. multi-page sites. Service workers have been designed to avoid these common pain
  27. points.</p>
  28. <p>Things to note about a service worker:</p>
  29. <ul>
  30. <li>It's a <a href="/tutorials/workers/basics/">JavaScript
  31. Worker</a>, so it can't
  32. access the DOM directly. Instead, a service worker can communicate with the
  33. pages it controls by responding to messages sent via the
  34. <a href="https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage"><code>postMessage</code></a>
  35. interface, and those pages can manipulate the DOM if needed.</li>
  36. <li>Service worker is a programmable network proxy, allowing you to control
  37. how network requests from your page are handled.</li>
  38. <li>It will be terminated when not in use, and restarted when it's next needed, so
  39. you cannot rely on global state within a service worker's <code>onfetch</code> and
  40. <code>onmessage</code> handlers. If there is information that you need to persist and
  41. reuse across restarts, service workers do have access to the
  42. <a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a>
  43. API.</li>
  44. <li>Service workers make extensive use of promises, so if you're new to promises,
  45. then you should stop reading this and check out <a href="/tutorials/es6/promises/">Jake Archibald's
  46. article</a>.</li>
  47. </ul>
  48. <h2 id="lifecycle">Service Worker Lifecycle</h2>
  49. <p>A service worker has a lifecycle which is completely separate from your web
  50. page.</p>
  51. <p>To install a service worker for your site, you need to <strong>register</strong> it, which
  52. you do in your page's JavaScript. Registering a service worker will cause the
  53. browser to start the service worker install step in the background.</p>
  54. <p>Typically during the install step, you'll want to cache some static assets. If
  55. all the files are cached successfully, then the service worker becomes
  56. installed. If any of the files fail to download and cache, then the install step
  57. will fail and the service worker won't activate (i.e. won't be installed). If
  58. that happens, don't worry, it'll try again next time. But that means if it
  59. <em>does</em> install, you <strong>know</strong> you've got those static assets in the cache.</p>
  60. <p>When we're installed, the activation step will follow and this is a great
  61. opportunity for handling any management of old caches, which we'll cover during
  62. the <a href="#toc-how">service worker update section</a>.</p>
  63. <p>After the activation step, the service worker will control all pages that fall
  64. under its scope, though the page that registered the service worker for the
  65. first time won't be controlled until it's loaded again. Once a service worker is
  66. in control, it will be in one of two states: either the service worker will be
  67. terminated to save memory, or it will handle <code>fetch</code> and <code>message</code> events which
  68. occur when a network request or message is made from your page.</p>
  69. <p>Below is an overly simplified version of the service worker lifecycle on it's
  70. first installation.</p>
  71. <img src="http://www.html5rocks.com/en/tutorials/service-worker/introduction/images/sw-lifecycle.png"/>
  72. <h2 id="toc-before">Before We Start</h2>
  73. <p>Grab the caches polyfill from this repository
  74. <a href="https://github.com/coonsta/cache-polyfill">https://github.com/coonsta/cache-polyfill</a>.</p>
  75. <p>This polyfill will add support for <code>Cache.addAll</code> which Chrome M43's implementation of
  76. the <a href="https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache-interface">Cache
  77. API</a> doesn't currently support.</p>
  78. <p>Grab <strong><code>dist/serviceworker-cache-polyfill.js</code></strong> to put somewhere in your site
  79. and use it in a service worker with the <strong><code>importScripts</code></strong> method. Any script
  80. which is imported will automatically be cached by the service worker.</p>
  81. <pre class="prettyprint"><code>importScripts('serviceworker-cache-polyfill.js');</code></pre>
  82. <h3>HTTPS is Needed</h3>
  83. <p>During development you'll be able to use service worker through <code>localhost</code>, but
  84. to deploy it on a site you'll need to have HTTPS setup on your server.</p>
  85. <p>Using service worker you can hijack connections, fabricate, and filter
  86. responses. Powerful stuff. While you would use these powers for good, a
  87. man-in-the-middle might not. To avoid this, you can only register for service
  88. workers on pages served over HTTPS, so we know the service worker the browser
  89. receives hasn't been tampered with during its journey through the network.</p>
  90. <p><a href="https://pages.github.com/">Github
  91. Pages</a> are served over HTTPS, so they're a great place to host demos.</p>
  92. <p>If you want to add HTTPS to your server then you'll need to get a TLS
  93. certificate and set it up for your server. This varies depending on your setup,
  94. so check your server's documentation and be sure to check out <a href="https://mozilla.github.io/server-side-tls/ssl-config-generator/">Mozilla's SSL config generator</a> for best practices.</p>
  95. <h3>Using Service Worker</h3>
  96. <p>Now that we've got the Polyfill and covered HTTPS, let's look at what we do in
  97. each step.</p>
  98. <h3>How to Register and Install a Service Worker</h3>
  99. <p>To install a service worker you need to kick start the process by <strong>registering</strong>
  100. a service worker in your page. This tells the browser where your service
  101. worker JavaScript file lives.</p>
  102. <pre class="prettyprint"><code>if ('serviceWorker' in navigator) {
  103. navigator.serviceWorker.register('/sw.js').then(function(registration) {
  104. // Registration was successful
  105. console.log('ServiceWorker registration successful with scope: ', registration.scope);
  106. }).catch(function(err) {
  107. // registration failed :(
  108. console.log('ServiceWorker registration failed: ', err);
  109. });
  110. }</code></pre>
  111. <p>This code checks to see if the service worker API is available, and if it is,
  112. the service worker at <code>/sw.js</code> is registered.</p>
  113. <p>You can call register every time a page loads without concern; the browser will
  114. figure out if the service worker is already registered or not and handle it
  115. accordingly.</p>
  116. <p>One subtlety with the register method is the location of the service worker
  117. file. You'll notice in this case that the service worker file is at the root of
  118. the domain. This means that the service worker's scope will be the entire
  119. origin. In other words, this service worker will receive <code>fetch</code> events for
  120. everything on this domain. If we register the service worker file at
  121. <code>/example/sw.js</code>, then the service worker would only see <code>fetch</code> events for
  122. pages whose URL starts with <code>/example/</code> (i.e. <code>/example/page1/</code>,
  123. <code>/example/page2/</code>).</p>
  124. <p>Now you can check that a service worker is enabled by going to
  125. <code>chrome://inspect/#service-workers</code> and looking for your site.</p>
  126. <img src="http://www.html5rocks.com/en/tutorials/service-worker/introduction/images/sw-chrome-inspect.png"/>
  127. <p>When service worker was first being implemented you could also view your service
  128. worker details through <code>chrome://serviceworker-internals</code>. This may still be
  129. useful, if for nothing more than learning about the life cycle of service
  130. workers, but don't be surprised if it gets replaced by
  131. <code>chrome://inspect/#service-workers</code> at a later date.</p>
  132. <p>You may find it useful to test your service worker in an Incognito window so
  133. that you can close and reopen knowing that the previous service worker won't
  134. affect the new window. Any registrations and caches created from within an
  135. Incognito window will be cleared out once that window is closed.</p>
  136. <h3>Service Worker Install Step</h3>
  137. <p>After a controlled page kicks off the registration process, let's shift to the
  138. point of view of the service worker script, which is given the opportunity to
  139. handle the <code>install</code> event.</p>
  140. <p>For the most basic example, you need to define a callback for the <code>install</code> event
  141. and decide which files you want to cache.</p>
  142. <pre class="prettyprint"><code>// The files we want to cache
  143. var urlsToCache = [
  144. '/',
  145. '/styles/main.css',
  146. '/script/main.js'
  147. ];
  148. // Set the callback for the install step
  149. self.addEventListener('install', function(event) {
  150. // Perform install steps
  151. });</code></pre>
  152. <p>Inside of our install callback, we need to take the following steps:</p>
  153. <ol>
  154. <li>Open a cache</li>
  155. <li>Cache our files</li>
  156. <li>Confirm whether all the required assets are cached or not</li>
  157. </ol>
  158. <pre class="prettyprint"><code>var CACHE_NAME = 'my-site-cache-v1';
  159. var urlsToCache = [
  160. '/',
  161. '/styles/main.css',
  162. '/script/main.js'
  163. ];
  164. self.addEventListener('install', function(event) {
  165. // Perform install steps
  166. event.waitUntil(
  167. caches.open(CACHE_NAME)
  168. .then(function(cache) {
  169. console.log('Opened cache');
  170. return cache.addAll(urlsToCache);
  171. })
  172. );
  173. });</code></pre>
  174. <p>Here you can see we call <code>caches.open</code> with our desired cache name, after this we
  175. call <code>cache.addAll</code> and pass in our array of files. This is a chain of promises
  176. (<code>caches.open</code> and <code>cache.addAll</code>). <code>event.waitUntil</code> takes a promise and uses it
  177. to know how long installation takes, and whether it succeeded.</p>
  178. <p>If all the files are successfully cached, then the service worker
  179. will be installed. If <strong>any</strong> of the files fail to download, then the install
  180. step will fail. This allows you to rely on having all the assets that you
  181. defined, but does mean you need to be careful with the list of files you decide
  182. to cache in the install step. Defining a long list of files will increase the
  183. chance that one file may fail to cache, leading to your service worker not
  184. getting installed.</p>
  185. <p>This is just one example, you can perform other tasks in the <code>install</code> event or
  186. avoid setting an <code>install</code> event listener altogether.</p>
  187. <h3>How to Cache and Return Requests</h3>
  188. <p>Now that you've installed a service worker, you probably want to return one of
  189. your cached responses right?</p>
  190. <p>After a service worker is installed and the user navigates to a different page
  191. or refreshes, the service worker will begin to receive <code>fetch</code> events, an example
  192. of which is below.</p>
  193. <pre class="prettyprint"><code>self.addEventListener('fetch', function(event) {
  194. event.respondWith(
  195. caches.match(event.request)
  196. .then(function(response) {
  197. // Cache hit - return response
  198. if (response) {
  199. return response;
  200. }
  201. return fetch(event.request);
  202. }
  203. )
  204. );
  205. });</code></pre>
  206. <p>Here we've defined our <code>fetch</code> event and within the <code>event.respondWith</code>, we pass
  207. in a promise from <code>caches.match</code>. <code>caches.match</code> will look at the request
  208. and find any cached results from any of the caches your service worker created.</p>
  209. <p>If we have a matching response, we return the cached value, otherwise we return
  210. the result of a call to <code>fetch</code>, which will make a network request and return the
  211. data if anything can be retrieved from the network. This is a simple example and
  212. uses any cached assets we cached during the install step.</p>
  213. <p>If we wanted to cache new requests cumulatively, we can do so by handling the
  214. response of the fetch request and then adding it to the cache, like below.</p>
  215. <pre class="prettyprint"><code>self.addEventListener('fetch', function(event) {
  216. event.respondWith(
  217. caches.match(event.request)
  218. .then(function(response) {
  219. // Cache hit - return response
  220. if (response) {
  221. return response;
  222. }
  223. // IMPORTANT: Clone the request. A request is a stream and
  224. // can only be consumed once. Since we are consuming this
  225. // once by cache and once by the browser for fetch, we need
  226. // to clone the response
  227. var fetchRequest = event.request.clone();
  228. return fetch(fetchRequest).then(
  229. function(response) {
  230. // Check if we received a valid response
  231. if(!response || response.status !== 200 || response.type !== 'basic') {
  232. return response;
  233. }
  234. // IMPORTANT: Clone the response. A response is a stream
  235. // and because we want the browser to consume the response
  236. // as well as the cache consuming the response, we need
  237. // to clone it so we have 2 stream.
  238. var responseToCache = response.clone();
  239. caches.open(CACHE_NAME)
  240. .then(function(cache) {
  241. cache.put(event.request, responseToCache);
  242. });
  243. return response;
  244. }
  245. );
  246. })
  247. );
  248. });</code></pre>
  249. <p>What we are doing is this:</p>
  250. <ol>
  251. <li>Add a callback to <code>.then</code> on the fetch request</li>
  252. <li>Once we get a response, we perform the following checks:</li>
  253. <ol>
  254. <li>Ensure the response is valid.</li>
  255. <li>Check the status is <code>200</code> on the response.</li>
  256. <li>Make sure the response type is <strong>basic</strong>, which indicates that it's a
  257. request from our origin. This means that requests to third party assets
  258. aren't cached as well.</li>
  259. </ol>
  260. <li>If we pass the checks, we
  261. <a href="https://fetch.spec.whatwg.org/#dom-response-clone"><code>clone</code></a>
  262. the response. The reason for this is that because the response is a
  263. <a href="https://streams.spec.whatwg.org/">Stream</a>,
  264. the body can only be consumed once. Since we want to return the
  265. response for the browser to use, as well as pass it to the cache to use, we
  266. need to clone it so we can send one to the browser and one to the cache.</li>
  267. </ol>
  268. <h2 id="toc-how">How to Update a Service Worker</h2>
  269. <p>There will be a point in time where your service worker will need updating. When that time comes, you'll need to follow these steps:</p>
  270. <ol>
  271. <li>Update your service worker JavaScript file.</li>
  272. <ol>
  273. <li>When the user navigates to your site, the browser tries to redownload the
  274. script file that defined the service worker in the background. If there
  275. is even a byte's difference in the service worker file compared to what
  276. it currently has, it considers it 'new'.</li>
  277. </ol>
  278. <li>Your new service worker will be started and the <code>install</code> event will be fired.</li>
  279. <li>At this point the old service worker is still controlling the current pages
  280. so the new service worker will enter a "waiting" state.</li>
  281. <li>When the currently open pages of your site are closed, the old service worker
  282. will be killed and the new service worker will take control.</li>
  283. <li>Once your new service worker takes control, its <code>activate</code> event will be fired.</li>
  284. </ol>
  285. <p>One common task that will occur in the activate callback is cache management.
  286. The reason you'll want to do this in the activate callback is because if you
  287. were to wipe out any old caches in the install step, any old service worker,
  288. which keeps control of all the current pages, will suddenly stop being able to
  289. serve files from that cache.</p>
  290. <p>Let's say we have one cache called 'my-site-cache-v1', and we find that we want
  291. to split this out into one cache for pages and one cache for blog posts. This
  292. means in the install step we'd create two caches, 'pages-cache-v1' and
  293. 'blog-posts-cache-v1' and in the activate step we'd want to delete our older
  294. 'my-site-cache-v1'.</p>
  295. <p>The following code would do this by looping through all of the caches in the
  296. service worker and deleting any caches which aren't defined in the cache
  297. whitelist.</p>
  298. <pre class="prettyprint"><code>self.addEventListener('activate', function(event) {
  299. var cacheWhitelist = ['pages-cache-v1', 'blog-posts-cache-v1'];
  300. event.waitUntil(
  301. caches.keys().then(function(cacheNames) {
  302. return Promise.all(
  303. cacheNames.map(function(cacheName) {
  304. if (cacheWhitelist.indexOf(cacheName) === -1) {
  305. return caches.delete(cacheName);
  306. }
  307. })
  308. );
  309. })
  310. );
  311. });</code></pre>
  312. <h2 id="toc-rough">Rough Edges &amp; Gotchas</h2>
  313. <p>This stuff is really new. Here's a collection of issues that get in the way.
  314. Hopefully this section can be deleted soon, but for now these are worth being
  315. mindful of.</p>
  316. <h3>If Installation Fails, We're Not so Good at Telling You About It</h3>
  317. <p>If a worker registers, but then doesn't appear in
  318. <code>chrome://inspect/#service-workers</code> or <code>chrome://serviceworker-internals</code>, it's
  319. likely its failed to install due to an error being thrown, or a rejected promise
  320. being passed to <code>event.waitUntil</code>.</p>
  321. <p>To work around this, go to <code>chrome://serviceworker-internals</code> and check "Opens the
  322. DevTools window for service worker on start for debugging", and put a debugger;
  323. statement at the start of your <code>install</code> event. This, along with "<a href="https://developer.chrome.com/devtools/docs/javascript-debugging#pause-on-uncaught-exceptions">
  324. Pause on uncaught exceptions</a>", should reveal the issue.</p>
  325. <h3>The Defaults of fetch()</h3>
  326. <h4>No Credentials by Default</h4>
  327. <p>When you use <code>fetch</code>, by default, requests won't contain credentials such as
  328. cookies. If you want credentials, instead call:</p>
  329. <pre class="prettyprint"><code>fetch(url, {
  330. credentials: 'include'
  331. })</code></pre>
  332. <p>This behaviour is on purpose, and is arguably better than XHR's more complex
  333. default of sending credentials if the URL is same-origin, but omiting them
  334. otherwise. Fetch's behaviour is more like other CORS requests, such as <code>&lt;img crossorigin&gt;</code>, which never sends cookies unless you opt-in with <code>&lt;img crossorigin="use-credentials"&gt;</code>.</p>
  335. <h4>Non-CORS Fail by Default</h4>
  336. <p>By default, fetching a resource from a third party URL will fail if it doesn't
  337. support CORS. You can add a non-CORS option to the <code>Request</code> to overcome this,
  338. although this will cause an <a href="https://fetch.spec.whatwg.org/#concept-filtered-response-opaque">'opaque'
  339. response</a>,
  340. which means you won't be able to tell if the response was successful or not.</p>
  341. <pre class="prettyprint"><code>cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {
  342. return new Request(urlToPrefetch, { mode: 'no-cors' });
  343. })).then(function() {
  344. console.log('All resources have been fetched and cached.');
  345. });</code></pre>
  346. <h3>Handling Responsive Images</h3>
  347. <p>The <code>srcset</code> attribute or the <code>&lt;picture&gt;</code> element
  348. will select the most appropriate image asset at run time and make a network request.</p>
  349. <p>For service worker, if you wanted to cache an image during the install step, you
  350. have a few options:</p>
  351. <ol>
  352. <li>Install all the images <code>&lt;picture&gt;</code> element and <code>srcset</code> attribute will request</li>
  353. <li>Install a single low-res version of the image</li>
  354. <li>Install a single high-res version of the image</li>
  355. </ol>
  356. <p>Realistically you should be picking option 2 or 3 since downloading all of the
  357. images would be a waste of memory.</p>
  358. <p>Let's assume you go for the low res version at install time and you want to try
  359. and retrieve higher res images from the network when the page is loaded, but if
  360. the high res images fail, fallback to the low res version. This is fine and
  361. dandy to do but there is one problem.</p>
  362. <p>If we have the following two images:</p>
  363. <table>
  364. <tr>
  365. <td>Screen Density</td>
  366. <td>Width</td>
  367. <td>Height</td>
  368. </tr>
  369. <tr>
  370. <td>1x</td>
  371. <td>400</td>
  372. <td>400</td>
  373. </tr>
  374. <tr>
  375. <td>2x</td>
  376. <td>800</td>
  377. <td>800</td>
  378. </tr>
  379. </table>
  380. <p>In a srcset image, we'd have some markup like this:</p>
  381. <pre class="prettyprint"><code>&lt;img src="image-src.png" srcset="image-src.png 1x, image-2x.png 2x" /&gt;</code></pre>
  382. <p>If we are on a 2x display, then the browser will opt to download <code>image-2x.png</code>,
  383. if we are offline you could <code>.catch</code> this request and return <code>image-src.png</code>
  384. instead if it's cached, however the browser will expect an image which
  385. takes into account the extra pixels on a 2x screen, so the image will appear as
  386. 200x200 CSS pixels instead of 400x400 CSS pixels. The only way around this is to
  387. set a fixed height and width on the image.</p>
  388. <pre class="prettyprint"><code>&lt;img src="image-src.png" srcset="image-src.png 1x, image-2x.png 2x"
  389. style="width:400px; height: 400px;" /&gt;</code></pre>
  390. <img src="http://www.html5rocks.com/en/tutorials/service-worker/introduction/images/sw-responsive-img-example.png"/>
  391. <p>For <code>&lt;picture&gt;</code> elements being used for art direction, this becomes considerably
  392. more difficult and will depend heavily on how your images are created and used,
  393. but you may be able to use a similar approach to srcset.</p>
  394. <h2 id="toc-learn">Learn More</h2>
  395. <p>There is a list of documentation on service worker being maintained at
  396. <a href="https://jakearchibald.github.io/isserviceworkerready/resources.html">https://jakearchibald.github.io/isserviceworkerready/resources.html</a>
  397. that you may find useful.</p>
  398. <h2 id="toc-help">Get Help</h2>
  399. <p>If you get stuck then please post your questions on Stackoverflow and use the
  400. <a href="http://stackoverflow.com/questions/tagged/service-worker">'service-worker'</a>
  401. tag so that we can keep a track of issues and try and help as much as possible.</p>