12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025 |
- <!doctype html><!-- This is a valid HTML5 document. -->
- <!-- Screen readers, SEO, extensions and so on. -->
- <html lang=fr>
- <!-- Has to be within the first 1024 bytes, hence before the <title>
- See: https://www.w3.org/TR/2012/CR-html5-20121217/document-metadata.html#charset -->
- <meta charset=utf-8>
- <!-- Why no `X-UA-Compatible` meta: https://stackoverflow.com/a/6771584 -->
- <!-- The viewport meta is quite crowded and we are responsible for that.
- See: https://codepen.io/tigt/post/meta-viewport-for-2015 -->
- <meta name=viewport content="width=device-width,minimum-scale=1,initial-scale=1,shrink-to-fit=no">
- <!-- Required to make a valid HTML5 document. -->
- <title>Introduction to Service Worker (archive) — David Larlet</title>
- <!-- Generated from https://realfavicongenerator.net/ such a mess. -->
- <link rel="apple-touch-icon" sizes="180x180" href="/static/david/icons/apple-touch-icon.png">
- <link rel="icon" type="image/png" sizes="32x32" href="/static/david/icons/favicon-32x32.png">
- <link rel="icon" type="image/png" sizes="16x16" href="/static/david/icons/favicon-16x16.png">
- <link rel="manifest" href="/manifest.json">
- <link rel="mask-icon" href="/static/david/icons/safari-pinned-tab.svg" color="#5bbad5">
- <link rel="shortcut icon" href="/static/david/icons/favicon.ico">
- <meta name="apple-mobile-web-app-title" content="David Larlet">
- <meta name="application-name" content="David Larlet">
- <meta name="msapplication-TileColor" content="#da532c">
- <meta name="msapplication-config" content="/static/david/icons/browserconfig.xml">
- <meta name="theme-color" content="#f0f0ea">
- <!-- That good ol' feed, subscribe :p. -->
- <link rel=alternate type="application/atom+xml" title=Feed href="/david/log/">
-
- <meta name="robots" content="noindex, nofollow">
- <meta content="origin-when-cross-origin" name="referrer">
- <!-- Canonical URL for SEO purposes -->
- <link rel="canonical" href="http://www.html5rocks.com/en/tutorials/service-worker/introduction/">
-
- <style>
- /* http://meyerweb.com/eric/tools/css/reset/ */
- html, body, div, span,
- h1, h2, h3, h4, h5, h6, p, blockquote, pre,
- a, abbr, address, big, cite, code,
- del, dfn, em, img, ins,
- small, strike, strong, tt, var,
- dl, dt, dd, ol, ul, li,
- fieldset, form, label, legend,
- table, caption, tbody, tfoot, thead, tr, th, td,
- article, aside, canvas, details, embed,
- figure, figcaption, footer, header, hgroup,
- menu, nav, output, ruby, section, summary,
- time, mark, audio, video {
- margin: 0;
- padding: 0;
- border: 0;
- font-size: 100%;
- font: inherit;
- vertical-align: baseline;
- }
- /* HTML5 display-role reset for older browsers */
- article, aside, details, figcaption, figure,
- footer, header, hgroup, menu, nav, section { display: block; }
- body { line-height: 1; }
- blockquote, q { quotes: none; }
- blockquote:before, blockquote:after,
- q:before, q:after {
- content: '';
- content: none;
- }
- table {
- border-collapse: collapse;
- border-spacing: 0;
- }
-
- /* http://practicaltypography.com/equity.html */
- /* https://calendar.perfplanet.com/2016/no-font-face-bulletproof-syntax/ */
- /* https://www.filamentgroup.com/lab/js-web-fonts.html */
- @font-face {
- font-family: 'EquityTextB';
- src: url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff2') format('woff2'),
- url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff') format('woff');
- font-weight: 300;
- font-style: normal;
- font-display: swap;
- }
- @font-face {
- font-family: 'EquityTextB';
- src: url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff2') format('woff2'),
- url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff') format('woff');
- font-weight: 300;
- font-style: italic;
- font-display: swap;
- }
- @font-face {
- font-family: 'EquityTextB';
- src: url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff2') format('woff2'),
- url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff') format('woff');
- font-weight: 700;
- font-style: normal;
- font-display: swap;
- }
-
- @font-face {
- font-family: 'ConcourseT3';
- src: url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff2') format('woff2'),
- url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff') format('woff');
- font-weight: 300;
- font-style: normal;
- font-display: swap;
- }
-
-
- /* http://practice.typekit.com/lesson/caring-about-opentype-features/ */
- body {
- /* http://www.cssfontstack.com/ Palatino 99% Win 86% Mac */
- font-family: "EquityTextB", Palatino, serif;
- background-color: #f0f0ea;
- color: #07486c;
- font-kerning: normal;
- -moz-osx-font-smoothing: grayscale;
- -webkit-font-smoothing: subpixel-antialiased;
- text-rendering: optimizeLegibility;
- font-variant-ligatures: common-ligatures contextual;
- font-feature-settings: "kern", "liga", "clig", "calt";
- }
- pre, code, kbd, samp, var, tt {
- font-family: 'TriplicateT4c', monospace;
- }
- em {
- font-style: italic;
- color: #323a45;
- }
- strong {
- font-weight: bold;
- color: black;
- }
- nav {
- background-color: #323a45;
- color: #f0f0ea;
- display: flex;
- justify-content: space-around;
- padding: 1rem .5rem;
- }
- nav:last-child {
- border-bottom: 1vh solid #2d7474;
- }
- nav a {
- color: #f0f0ea;
- }
- nav abbr {
- border-bottom: 1px dotted white;
- }
-
- h1 {
- border-top: 1vh solid #2d7474;
- border-bottom: .2vh dotted #2d7474;
- background-color: #e3e1e1;
- color: #323a45;
- text-align: center;
- padding: 5rem 0 4rem 0;
- width: 100%;
- font-family: 'ConcourseT3';
- display: flex;
- flex-direction: column;
- }
- h1.single {
- padding-bottom: 10rem;
- }
- h1 span {
- position: absolute;
- top: 1vh;
- left: 20%;
- line-height: 0;
- }
- h1 span a {
- line-height: 1.7;
- padding: 1rem 1.2rem .6rem 1.2rem;
- border-radius: 0 0 6% 6%;
- background: #2d7474;
- font-size: 1.3rem;
- color: white;
- text-decoration: none;
- }
- h2 {
- margin: 4rem 0 1rem;
- border-top: .2vh solid #2d7474;
- padding-top: 1vh;
- }
- h3 {
- text-align: center;
- margin: 3rem 0 .75em;
- }
- hr {
- height: .4rem;
- width: .4rem;
- border-radius: .4rem;
- background: #07486c;
- margin: 2.5rem auto;
- }
- time {
- display: bloc;
- margin-left: 0 !important;
- }
- ul, ol {
- margin: 2rem;
- }
- ul {
- list-style-type: square;
- }
- a {
- text-decoration-skip-ink: auto;
- text-decoration-thickness: 0.05em;
- text-underline-offset: 0.09em;
- }
- article {
- max-width: 50rem;
- display: flex;
- flex-direction: column;
- margin: 2rem auto;
- }
- article.single {
- border-top: .2vh dotted #2d7474;
- margin: -6rem auto 1rem auto;
- background: #f0f0ea;
- padding: 2rem;
- }
- article p:last-child {
- margin-bottom: 1rem;
- }
- p {
- padding: 0 .5rem;
- margin-left: 3rem;
- }
- p + p,
- figure + p {
- margin-top: 2rem;
- }
-
- blockquote {
- background-color: #e3e1e1;
- border-left: .5vw solid #2d7474;
- display: flex;
- flex-direction: column;
- align-items: center;
- padding: 1rem;
- margin: 1.5rem;
- }
- blockquote cite {
- font-style: italic;
- }
- blockquote p {
- margin-left: 0;
- }
-
- figure {
- border-top: .2vh solid #2d7474;
- background-color: #e3e1e1;
- text-align: center;
- padding: 1.5rem 0;
- margin: 1rem 0 0;
- font-size: 1.5rem;
- width: 100%;
- }
- figure img {
- max-width: 250px;
- max-height: 250px;
- border: .5vw solid #323a45;
- padding: 1px;
- }
- figcaption {
- padding: 1rem;
- line-height: 1.4;
- }
- aside {
- display: flex;
- flex-direction: column;
- background-color: #e3e1e1;
- padding: 1rem 0;
- border-bottom: .2vh solid #07486c;
- }
- aside p {
- max-width: 50rem;
- margin: 0 auto;
- }
-
- /* https://fvsch.com/code/css-locks/ */
- p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
- font-size: 1rem;
- line-height: calc( 1.5em + 0.2 * 1rem );
- }
- h1 {
- font-size: 1.9rem;
- line-height: calc( 1.2em + 0.2 * 1rem );
- }
- h2 {
- font-size: 1.6rem;
- line-height: calc( 1.3em + 0.2 * 1rem );
- }
- h3 {
- font-size: 1.35rem;
- line-height: calc( 1.4em + 0.2 * 1rem );
- }
- @media (min-width: 20em) {
- /* The (100vw - 20rem) / (50 - 20) part
- resolves to 0-1rem, depending on the
- viewport width (between 20em and 50em). */
- p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
- font-size: calc( 1rem + .6 * (100vw - 20rem) / (50 - 20) );
- line-height: calc( 1.5em + 0.2 * (100vw - 50rem) / (20 - 50) );
- margin-left: 0;
- }
- h1 {
- font-size: calc( 1.9rem + 1.5 * (100vw - 20rem) / (50 - 20) );
- line-height: calc( 1.2em + 0.2 * (100vw - 50rem) / (20 - 50) );
- }
- h2 {
- font-size: calc( 1.5rem + 1.5 * (100vw - 20rem) / (50 - 20) );
- line-height: calc( 1.3em + 0.2 * (100vw - 50rem) / (20 - 50) );
- }
- h3 {
- font-size: calc( 1.35rem + 1.5 * (100vw - 20rem) / (50 - 20) );
- line-height: calc( 1.4em + 0.2 * (100vw - 50rem) / (20 - 50) );
- }
- }
- @media (min-width: 50em) {
- /* The right part of the addition *must* be a
- rem value. In this example we *could* change
- the whole declaration to font-size:2.5rem,
- but if our baseline value was not expressed
- in rem we would have to use calc. */
- p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
- font-size: calc( 1rem + .6 * 1rem );
- line-height: 1.5em;
- }
- p, li, pre, details {
- margin-left: 3rem;
- }
- h1 {
- font-size: calc( 1.9rem + 1.5 * 1rem );
- line-height: 1.2em;
- }
- h2 {
- font-size: calc( 1.5rem + 1.5 * 1rem );
- line-height: 1.3em;
- }
- h3 {
- font-size: calc( 1.35rem + 1.5 * 1rem );
- line-height: 1.4em;
- }
- figure img {
- max-width: 500px;
- max-height: 500px;
- }
- }
-
- figure.unsquared {
- margin-bottom: 1.5rem;
- }
- figure.unsquared img {
- height: inherit;
- }
-
-
-
- @media print {
- body { font-size: 100%; }
- a:after { content: " (" attr(href) ")"; }
- a, a:link, a:visited, a:after {
- text-decoration: underline;
- text-shadow: none !important;
- background-image: none !important;
- background: white;
- color: black;
- }
- abbr[title] { border-bottom: 0; }
- abbr[title]:after { content: " (" attr(title) ")"; }
- img { page-break-inside: avoid; }
- @page { margin: 2cm .5cm; }
- h1, h2, h3 { page-break-after: avoid; }
- p3 { orphans: 3; widows: 3; }
- img {
- max-width: 250px !important;
- max-height: 250px !important;
- }
- nav, aside { display: none; }
- }
-
- ul.with_columns {
- column-count: 1;
- }
- @media (min-width: 20em) {
- ul.with_columns {
- column-count: 2;
- }
- }
- @media (min-width: 50em) {
- ul.with_columns {
- column-count: 3;
- }
- }
- ul.with_two_columns {
- column-count: 1;
- }
- @media (min-width: 20em) {
- ul.with_two_columns {
- column-count: 1;
- }
- }
- @media (min-width: 50em) {
- ul.with_two_columns {
- column-count: 2;
- }
- }
-
- .gallery {
- display: flex;
- flex-wrap: wrap;
- justify-content: space-around;
- }
- .gallery figure img {
- margin-left: 1rem;
- margin-right: 1rem;
- }
- .gallery figure figcaption {
- font-family: 'ConcourseT3'
- }
-
- footer {
- font-family: 'ConcourseT3';
- display: flex;
- flex-direction: column;
- border-top: 3px solid white;
- padding: 4rem 0;
- background-color: #07486c;
- color: white;
- }
- footer > * {
- max-width: 50rem;
- margin: 0 auto;
- }
- footer a {
- color: #f1c40f;
- }
- footer .avatar {
- width: 200px;
- height: 200px;
- border-radius: 50%;
- float: left;
- -webkit-shape-outside: circle();
- shape-outside: circle();
- margin-right: 2rem;
- padding: 2px 5px 5px 2px;
- background: white;
- border-left: 1px solid #f1c40f;
- border-top: 1px solid #f1c40f;
- border-right: 5px solid #f1c40f;
- border-bottom: 5px solid #f1c40f;
- }
- </style>
-
- <h1>
- <span><a id="jumper" href="#jumpto" title="Un peu perdu ?">?</a></span>
- Introduction to Service Worker (archive)
- <time>Pour la pérennité des contenus liés. Non-indexé, retrait sur simple email.</time>
- </h1>
- <section>
- <article>
- <h3><a href="http://www.html5rocks.com/en/tutorials/service-worker/introduction/">Source originale du contenu</a></h3>
- <p>Rich offline experiences, periodic background syncs, push notifications—
- functionality that would normally require a native application—are coming to
- the web. Service workers provide the technical foundation that all these
- features will rely on.</p>
-
- <h2 id="toc-what">What is a Service Worker?</h2>
-
- <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. Today, they already include features like
- <a href="http://updates.html5rocks.com/2015/03/push-notificatons-on-the-open-web">
- push notifications</a> and in the future it will include other things like,
- background sync, or geofencing. The core feature discussed in this tutorial is
- the ability to intercept and handle network requests, including programmatically
- managing a cache of responses.</p>
-
- <p>The reason this is such an exciting API is that it allows you to support offline
- experiences, giving developers complete control over what exactly that
- experience is.</p>
-
- <p>Before service worker there was one other API that would give users an offline
- experience on the web called <a href="/tutorials/appcache/beginner/">App
- Cache</a>. The major
- issue with App Cache is the <a href="http://alistapart.com/article/application-cache-is-a-douchebag">number
- of gotcha's that exist</a> as well
- as the design working particularly well for single page web apps, but not for
- multi-page sites. Service workers have been designed to avoid these common pain
- points.</p>
-
- <p>Things to note about a service worker:</p>
-
- <ul>
- <li>It's a <a href="/tutorials/workers/basics/">JavaScript
- Worker</a>, so it can't
- access the DOM directly. Instead, a service worker can communicate with the
- pages it controls by responding to messages sent via the
- <a href="https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage"><code>postMessage</code></a>
- interface, and those pages can manipulate the DOM if needed.</li>
- <li>Service worker is a programmable network proxy, allowing you to control
- how network requests from your page are handled.</li>
- <li>It will be terminated when not in use, and restarted when it's next needed, so
- you cannot rely on global state within a service worker's <code>onfetch</code> and
- <code>onmessage</code> handlers. If there is information that you need to persist and
- reuse across restarts, service workers do have access to the
- <a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a>
- API.</li>
- <li>Service workers make extensive use of promises, so if you're new to promises,
- then you should stop reading this and check out <a href="/tutorials/es6/promises/">Jake Archibald's
- article</a>.</li>
- </ul>
-
- <h2 id="lifecycle">Service Worker Lifecycle</h2>
-
- <p>A service worker has a lifecycle which is completely separate from your web
- page.</p>
-
- <p>To install a service worker for your site, you need to <strong>register</strong> it, which
- you do in your page's JavaScript. Registering a service worker will cause the
- browser to start the service worker install step in the background.</p>
-
- <p>Typically during the install step, you'll want to cache some static assets. If
- all the files are cached successfully, then the service worker becomes
- installed. If any of the files fail to download and cache, then the install step
- will fail and the service worker won't activate (i.e. won't be installed). If
- that happens, don't worry, it'll try again next time. But that means if it
- <em>does</em> install, you <strong>know</strong> you've got those static assets in the cache.</p>
-
- <p>When we're installed, the activation step will follow and this is a great
- opportunity for handling any management of old caches, which we'll cover during
- the <a href="#toc-how">service worker update section</a>.</p>
-
- <p>After the activation step, the service worker will control all pages that fall
- under its scope, though the page that registered the service worker for the
- first time won't be controlled until it's loaded again. Once a service worker is
- in control, it will be in one of two states: either the service worker will be
- terminated to save memory, or it will handle <code>fetch</code> and <code>message</code> events which
- occur when a network request or message is made from your page.</p>
-
- <p>Below is an overly simplified version of the service worker lifecycle on it's
- first installation.</p>
-
- <p><img src="http://www.html5rocks.com/en/tutorials/service-worker/introduction/images/sw-lifecycle.png"/></p>
- <h2 id="toc-before">Before We Start</h2>
-
- <p>Grab the caches polyfill from this repository
- <a href="https://github.com/coonsta/cache-polyfill">https://github.com/coonsta/cache-polyfill</a>.</p>
-
- <p>This polyfill will add support for <code>Cache.addAll</code> which Chrome M43's implementation of
- the <a href="https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache-interface">Cache
- API</a> doesn't currently support.</p>
-
- <p>Grab <strong><code>dist/serviceworker-cache-polyfill.js</code></strong> to put somewhere in your site
- and use it in a service worker with the <strong><code>importScripts</code></strong> method. Any script
- which is imported will automatically be cached by the service worker.</p>
-
- <pre class="prettyprint"><code>importScripts('serviceworker-cache-polyfill.js');</code></pre>
-
- <h3>HTTPS is Needed</h3>
-
- <p>During development you'll be able to use service worker through <code>localhost</code>, but
- to deploy it on a site you'll need to have HTTPS setup on your server.</p>
-
- <p>Using service worker you can hijack connections, fabricate, and filter
- responses. Powerful stuff. While you would use these powers for good, a
- man-in-the-middle might not. To avoid this, you can only register for service
- workers on pages served over HTTPS, so we know the service worker the browser
- receives hasn't been tampered with during its journey through the network.</p>
-
- <p><a href="https://pages.github.com/">Github
- Pages</a> are served over HTTPS, so they're a great place to host demos.</p>
-
- <p>If you want to add HTTPS to your server then you'll need to get a TLS
- certificate and set it up for your server. This varies depending on your setup,
- 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>
-
- <h3>Using Service Worker</h3>
-
- <p>Now that we've got the Polyfill and covered HTTPS, let's look at what we do in
- each step.</p>
-
- <h3>How to Register and Install a Service Worker</h3>
-
- <p>To install a service worker you need to kick start the process by <strong>registering</strong>
- a service worker in your page. This tells the browser where your service
- worker JavaScript file lives.</p>
-
- <pre class="prettyprint"><code>if ('serviceWorker' in navigator) {
- navigator.serviceWorker.register('/sw.js').then(function(registration) {
- // Registration was successful
- console.log('ServiceWorker registration successful with scope: ', registration.scope);
- }).catch(function(err) {
- // registration failed :(
- console.log('ServiceWorker registration failed: ', err);
- });
- }</code></pre>
-
- <p>This code checks to see if the service worker API is available, and if it is,
- the service worker at <code>/sw.js</code> is registered.</p>
-
- <p>You can call register every time a page loads without concern; the browser will
- figure out if the service worker is already registered or not and handle it
- accordingly.</p>
-
- <p>One subtlety with the register method is the location of the service worker
- file. You'll notice in this case that the service worker file is at the root of
- the domain. This means that the service worker's scope will be the entire
- origin. In other words, this service worker will receive <code>fetch</code> events for
- everything on this domain. If we register the service worker file at
- <code>/example/sw.js</code>, then the service worker would only see <code>fetch</code> events for
- pages whose URL starts with <code>/example/</code> (i.e. <code>/example/page1/</code>,
- <code>/example/page2/</code>).</p>
-
- <p>Now you can check that a service worker is enabled by going to
- <code>chrome://inspect/#service-workers</code> and looking for your site.</p>
-
- <p><img src="http://www.html5rocks.com/en/tutorials/service-worker/introduction/images/sw-chrome-inspect.png"/></p>
- <p>When service worker was first being implemented you could also view your service
- worker details through <code>chrome://serviceworker-internals</code>. This may still be
- useful, if for nothing more than learning about the life cycle of service
- workers, but don't be surprised if it gets replaced by
- <code>chrome://inspect/#service-workers</code> at a later date.</p>
-
- <p>You may find it useful to test your service worker in an Incognito window so
- that you can close and reopen knowing that the previous service worker won't
- affect the new window. Any registrations and caches created from within an
- Incognito window will be cleared out once that window is closed.</p>
-
- <h3>Service Worker Install Step</h3>
-
- <p>After a controlled page kicks off the registration process, let's shift to the
- point of view of the service worker script, which is given the opportunity to
- handle the <code>install</code> event.</p>
-
- <p>For the most basic example, you need to define a callback for the <code>install</code> event
- and decide which files you want to cache.</p>
-
- <pre class="prettyprint"><code>// The files we want to cache
- var urlsToCache = [
- '/',
- '/styles/main.css',
- '/script/main.js'
- ];
-
- // Set the callback for the install step
- self.addEventListener('install', function(event) {
- // Perform install steps
- });</code></pre>
-
- <p>Inside of our install callback, we need to take the following steps:</p>
-
- <ol>
- <li>Open a cache</li>
- <li>Cache our files</li>
- <li>Confirm whether all the required assets are cached or not</li>
- </ol>
-
- <pre class="prettyprint"><code>var CACHE_NAME = 'my-site-cache-v1';
- var urlsToCache = [
- '/',
- '/styles/main.css',
- '/script/main.js'
- ];
-
- self.addEventListener('install', function(event) {
- // Perform install steps
- event.waitUntil(
- caches.open(CACHE_NAME)
- .then(function(cache) {
- console.log('Opened cache');
- return cache.addAll(urlsToCache);
- })
- );
- });</code></pre>
-
- <p>Here you can see we call <code>caches.open</code> with our desired cache name, after this we
- call <code>cache.addAll</code> and pass in our array of files. This is a chain of promises
- (<code>caches.open</code> and <code>cache.addAll</code>). <code>event.waitUntil</code> takes a promise and uses it
- to know how long installation takes, and whether it succeeded.</p>
-
- <p>If all the files are successfully cached, then the service worker
- will be installed. If <strong>any</strong> of the files fail to download, then the install
- step will fail. This allows you to rely on having all the assets that you
- defined, but does mean you need to be careful with the list of files you decide
- to cache in the install step. Defining a long list of files will increase the
- chance that one file may fail to cache, leading to your service worker not
- getting installed.</p>
-
- <p>This is just one example, you can perform other tasks in the <code>install</code> event or
- avoid setting an <code>install</code> event listener altogether.</p>
-
- <h3>How to Cache and Return Requests</h3>
-
- <p>Now that you've installed a service worker, you probably want to return one of
- your cached responses right?</p>
-
- <p>After a service worker is installed and the user navigates to a different page
- or refreshes, the service worker will begin to receive <code>fetch</code> events, an example
- of which is below.</p>
-
- <pre class="prettyprint"><code>self.addEventListener('fetch', function(event) {
- event.respondWith(
- caches.match(event.request)
- .then(function(response) {
- // Cache hit - return response
- if (response) {
- return response;
- }
-
- return fetch(event.request);
- }
- )
- );
- });</code></pre>
-
- <p>Here we've defined our <code>fetch</code> event and within the <code>event.respondWith</code>, we pass
- in a promise from <code>caches.match</code>. <code>caches.match</code> will look at the request
- and find any cached results from any of the caches your service worker created.</p>
-
- <p>If we have a matching response, we return the cached value, otherwise we return
- the result of a call to <code>fetch</code>, which will make a network request and return the
- data if anything can be retrieved from the network. This is a simple example and
- uses any cached assets we cached during the install step.</p>
-
- <p>If we wanted to cache new requests cumulatively, we can do so by handling the
- response of the fetch request and then adding it to the cache, like below.</p>
-
- <pre class="prettyprint"><code>self.addEventListener('fetch', function(event) {
- event.respondWith(
- caches.match(event.request)
- .then(function(response) {
- // Cache hit - return response
- if (response) {
- return response;
- }
-
- // IMPORTANT: Clone the request. A request is a stream and
- // can only be consumed once. Since we are consuming this
- // once by cache and once by the browser for fetch, we need
- // to clone the response
- var fetchRequest = event.request.clone();
-
- return fetch(fetchRequest).then(
- function(response) {
- // Check if we received a valid response
- if(!response || response.status !== 200 || response.type !== 'basic') {
- return response;
- }
-
- // IMPORTANT: Clone the response. A response is a stream
- // and because we want the browser to consume the response
- // as well as the cache consuming the response, we need
- // to clone it so we have 2 stream.
- var responseToCache = response.clone();
-
- caches.open(CACHE_NAME)
- .then(function(cache) {
- cache.put(event.request, responseToCache);
- });
-
- return response;
- }
- );
- })
- );
- });</code></pre>
-
- <p>What we are doing is this:</p>
-
- <ol>
- <li>Add a callback to <code>.then</code> on the fetch request</li>
- <li>Once we get a response, we perform the following checks:</li>
- <ol>
- <li>Ensure the response is valid.</li>
- <li>Check the status is <code>200</code> on the response.</li>
- <li>Make sure the response type is <strong>basic</strong>, which indicates that it's a
- request from our origin. This means that requests to third party assets
- aren't cached as well.</li>
- </ol>
- <li>If we pass the checks, we
- <a href="https://fetch.spec.whatwg.org/#dom-response-clone"><code>clone</code></a>
- the response. The reason for this is that because the response is a
- <a href="https://streams.spec.whatwg.org/">Stream</a>,
- the body can only be consumed once. Since we want to return the
- response for the browser to use, as well as pass it to the cache to use, we
- need to clone it so we can send one to the browser and one to the cache.</li>
- </ol>
-
- <h2 id="toc-how">How to Update a Service Worker</h2>
-
- <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>
-
- <ol>
- <li>Update your service worker JavaScript file.</li>
- <ol>
- <li>When the user navigates to your site, the browser tries to redownload the
- script file that defined the service worker in the background. If there
- is even a byte's difference in the service worker file compared to what
- it currently has, it considers it 'new'.</li>
- </ol>
- <li>Your new service worker will be started and the <code>install</code> event will be fired.</li>
- <li>At this point the old service worker is still controlling the current pages
- so the new service worker will enter a "waiting" state.</li>
- <li>When the currently open pages of your site are closed, the old service worker
- will be killed and the new service worker will take control.</li>
- <li>Once your new service worker takes control, its <code>activate</code> event will be fired.</li>
- </ol>
-
- <p>One common task that will occur in the activate callback is cache management.
- The reason you'll want to do this in the activate callback is because if you
- were to wipe out any old caches in the install step, any old service worker,
- which keeps control of all the current pages, will suddenly stop being able to
- serve files from that cache.</p>
-
- <p>Let's say we have one cache called 'my-site-cache-v1', and we find that we want
- to split this out into one cache for pages and one cache for blog posts. This
- means in the install step we'd create two caches, 'pages-cache-v1' and
- 'blog-posts-cache-v1' and in the activate step we'd want to delete our older
- 'my-site-cache-v1'.</p>
-
- <p>The following code would do this by looping through all of the caches in the
- service worker and deleting any caches which aren't defined in the cache
- whitelist.</p>
-
- <pre class="prettyprint"><code>self.addEventListener('activate', function(event) {
-
- var cacheWhitelist = ['pages-cache-v1', 'blog-posts-cache-v1'];
-
- event.waitUntil(
- caches.keys().then(function(cacheNames) {
- return Promise.all(
- cacheNames.map(function(cacheName) {
- if (cacheWhitelist.indexOf(cacheName) === -1) {
- return caches.delete(cacheName);
- }
- })
- );
- })
- );
- });</code></pre>
-
- <h2 id="toc-rough">Rough Edges & Gotchas</h2>
-
- <p>This stuff is really new. Here's a collection of issues that get in the way.
- Hopefully this section can be deleted soon, but for now these are worth being
- mindful of.</p>
-
- <h3>If Installation Fails, We're Not so Good at Telling You About It</h3>
-
- <p>If a worker registers, but then doesn't appear in
- <code>chrome://inspect/#service-workers</code> or <code>chrome://serviceworker-internals</code>, it's
- likely its failed to install due to an error being thrown, or a rejected promise
- being passed to <code>event.waitUntil</code>.</p>
-
- <p>To work around this, go to <code>chrome://serviceworker-internals</code> and check "Opens the
- DevTools window for service worker on start for debugging", and put a debugger;
- 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">
- Pause on uncaught exceptions</a>", should reveal the issue.</p>
-
- <h3>The Defaults of fetch()</h3>
-
- <h4>No Credentials by Default</h4>
-
- <p>When you use <code>fetch</code>, by default, requests won't contain credentials such as
- cookies. If you want credentials, instead call:</p>
-
- <pre class="prettyprint"><code>fetch(url, {
- credentials: 'include'
- })</code></pre>
-
- <p>This behaviour is on purpose, and is arguably better than XHR's more complex
- default of sending credentials if the URL is same-origin, but omiting them
- otherwise. Fetch's behaviour is more like other CORS requests, such as <code><img crossorigin></code>, which never sends cookies unless you opt-in with <code><img crossorigin="use-credentials"></code>.</p>
-
- <h4>Non-CORS Fail by Default</h4>
-
- <p>By default, fetching a resource from a third party URL will fail if it doesn't
- support CORS. You can add a non-CORS option to the <code>Request</code> to overcome this,
- although this will cause an <a href="https://fetch.spec.whatwg.org/#concept-filtered-response-opaque">'opaque'
- response</a>,
- which means you won't be able to tell if the response was successful or not.</p>
-
- <pre class="prettyprint"><code>cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {
- return new Request(urlToPrefetch, { mode: 'no-cors' });
- })).then(function() {
- console.log('All resources have been fetched and cached.');
- });</code></pre>
-
- <h3>Handling Responsive Images</h3>
-
- <p>The <code>srcset</code> attribute or the <code><picture></code> element
- will select the most appropriate image asset at run time and make a network request.</p>
-
- <p>For service worker, if you wanted to cache an image during the install step, you
- have a few options:</p>
-
- <ol>
- <li>Install all the images <code><picture></code> element and <code>srcset</code> attribute will request</li>
- <li>Install a single low-res version of the image</li>
- <li>Install a single high-res version of the image</li>
- </ol>
-
- <p>Realistically you should be picking option 2 or 3 since downloading all of the
- images would be a waste of memory.</p>
-
- <p>Let's assume you go for the low res version at install time and you want to try
- and retrieve higher res images from the network when the page is loaded, but if
- the high res images fail, fallback to the low res version. This is fine and
- dandy to do but there is one problem.</p>
-
- <p>If we have the following two images:</p>
-
- <table>
- <tr>
- <td>Screen Density</td>
- <td>Width</td>
- <td>Height</td>
- </tr>
- <tr>
- <td>1x</td>
- <td>400</td>
- <td>400</td>
- </tr>
- <tr>
- <td>2x</td>
- <td>800</td>
- <td>800</td>
- </tr>
- </table>
-
- <p>In a srcset image, we'd have some markup like this:</p>
-
- <pre class="prettyprint"><code><img src="image-src.png" srcset="image-src.png 1x, image-2x.png 2x" /></code></pre>
-
- <p>If we are on a 2x display, then the browser will opt to download <code>image-2x.png</code>,
- if we are offline you could <code>.catch</code> this request and return <code>image-src.png</code>
- instead if it's cached, however the browser will expect an image which
- takes into account the extra pixels on a 2x screen, so the image will appear as
- 200x200 CSS pixels instead of 400x400 CSS pixels. The only way around this is to
- set a fixed height and width on the image.</p>
-
- <pre class="prettyprint"><code><img src="image-src.png" srcset="image-src.png 1x, image-2x.png 2x"
- style="width:400px; height: 400px;" /></code></pre>
-
- <p><img src="http://www.html5rocks.com/en/tutorials/service-worker/introduction/images/sw-responsive-img-example.png"/></p>
- <p>For <code><picture></code> elements being used for art direction, this becomes considerably
- more difficult and will depend heavily on how your images are created and used,
- but you may be able to use a similar approach to srcset.</p>
-
- <h2 id="toc-learn">Learn More</h2>
-
- <p>There is a list of documentation on service worker being maintained at
- <a href="https://jakearchibald.github.io/isserviceworkerready/resources.html">https://jakearchibald.github.io/isserviceworkerready/resources.html</a>
- that you may find useful.</p>
-
- <h2 id="toc-help">Get Help</h2>
-
- <p>If you get stuck then please post your questions on Stackoverflow and use the
- <a href="http://stackoverflow.com/questions/tagged/service-worker">'service-worker'</a>
- tag so that we can keep a track of issues and try and help as much as possible.</p>
- </article>
- </section>
-
-
- <nav id="jumpto">
- <p>
- <a href="/david/blog/">Accueil du blog</a> |
- <a href="http://www.html5rocks.com/en/tutorials/service-worker/introduction/">Source originale</a> |
- <a href="/david/stream/2019/">Accueil du flux</a>
- </p>
- </nav>
-
- <footer>
- <div>
- <img src="/static/david/david-larlet-avatar.jpg" loading="lazy" class="avatar" width="200" height="200">
- <p>
- Bonjour/Hi!
- Je suis <a href="/david/" title="Profil public">David Larlet</a>, je vis actuellement à Montréal et j’alimente cet espace depuis 15 ans. <br>
- Si tu as apprécié cette lecture, n’hésite pas à poursuivre ton exploration. Par exemple via les <a href="/david/blog/" title="Expériences bienveillantes">réflexions bimestrielles</a>, la <a href="/david/stream/2019/" title="Pensées (dés)articulées">veille hebdomadaire</a> ou en t’abonnant au <a href="/david/log/" title="S’abonner aux publications via RSS">flux RSS</a> (<a href="/david/blog/2019/flux-rss/" title="Tiens c’est quoi un flux RSS ?">so 2005</a>).
- </p>
- <p>
- Je m’intéresse à la place que je peux avoir dans ce monde. En tant qu’humain, en tant que membre d’une famille et en tant qu’associé d’une coopérative. De temps en temps, je fais aussi des <a href="https://github.com/davidbgk" title="Principalement sur Github mais aussi ailleurs">trucs techniques</a>. Et encore plus rarement, <a href="/david/talks/" title="En ce moment je laisse plutôt la place aux autres">j’en parle</a>.
- </p>
-
- <p>
- Voici quelques articles choisis :
- <a href="/david/blog/2019/faire-equipe/" title="Accéder à l’article complet">Faire équipe</a>,
- <a href="/david/blog/2018/bivouac-automnal/" title="Accéder à l’article complet">Bivouac automnal</a>,
- <a href="/david/blog/2018/commodite-effondrement/" title="Accéder à l’article complet">Commodité et effondrement</a>,
- <a href="/david/blog/2017/donnees-communs/" title="Accéder à l’article complet">Des données aux communs</a>,
- <a href="/david/blog/2016/accompagner-enfant/" title="Accéder à l’article complet">Accompagner un enfant</a>,
- <a href="/david/blog/2016/senior-developer/" title="Accéder à l’article complet">Senior developer</a>,
- <a href="/david/blog/2016/illusion-sociale/" title="Accéder à l’article complet">L’illusion sociale</a>,
- <a href="/david/blog/2016/instantane-scopyleft/" title="Accéder à l’article complet">Instantané Scopyleft</a>,
- <a href="/david/blog/2016/enseigner-web/" title="Accéder à l’article complet">Enseigner le Web</a>,
- <a href="/david/blog/2016/simplicite-defaut/" title="Accéder à l’article complet">Simplicité par défaut</a>,
- <a href="/david/blog/2016/minimalisme-esthetique/" title="Accéder à l’article complet">Minimalisme et esthétique</a>,
- <a href="/david/blog/2014/un-web-omni-present/" title="Accéder à l’article complet">Un web omni-présent</a>,
- <a href="/david/blog/2014/manifeste-developpeur/" title="Accéder à l’article complet">Manifeste de développeur</a>,
- <a href="/david/blog/2013/confort-convivialite/" title="Accéder à l’article complet">Confort et convivialité</a>,
- <a href="/david/blog/2013/testament-numerique/" title="Accéder à l’article complet">Testament numérique</a>,
- et <a href="/david/blog/" title="Accéder aux archives">bien d’autres…</a>
- </p>
- <p>
- On peut <a href="mailto:david%40larlet.fr" title="Envoyer un courriel">échanger par courriel</a>. Si éventuellement tu souhaites que l’on travaille ensemble, tu devrais commencer par consulter le <a href="http://larlet.com">profil dédié à mon activité professionnelle</a> et/ou contacter directement <a href="http://scopyleft.fr/">scopyleft</a>, la <abbr title="Société coopérative et participative">SCOP</abbr> dont je fais partie depuis six ans. Je recommande au préalable de lire <a href="/david/blog/2018/cout-site/" title="Attention ce qui va suivre peut vous choquer">combien coûte un site</a> et pourquoi je suis plutôt favorable à une <a href="/david/pro/devis/" title="Discutons-en !">non-demande de devis</a>.
- </p>
- <p>
- Je ne traque pas ta navigation mais mon
- <abbr title="Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33.184162340">hébergeur</abbr>
- conserve des logs d’accès.
- </p>
- </div>
- </footer>
- <script type="text/javascript">
- ;(_ => {
- const jumper = document.getElementById('jumper')
- jumper.addEventListener('click', e => {
- e.preventDefault()
- const anchor = e.target.getAttribute('href')
- const targetEl = document.getElementById(anchor.substring(1))
- targetEl.scrollIntoView({behavior: 'smooth'})
- })
- })()
- </script>
|