├── README.md └── service-worker └── simple-service-worker ├── .prettierrc ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── app.js ├── gallery ├── bountyHunters.jpg ├── myLittleVader.jpg └── snowTroopers.jpg ├── image-list.js ├── index.html ├── star-wars-logo.jpg ├── style.css └── sw.js /README.md: -------------------------------------------------------------------------------- 1 | # sw-test 2 | 3 | > NOTE: This repository has been moved to [dom-examples/service-worker/simple-service-worker](https://github.com/mdn/dom-examples/tree/master/service-worker/simple-service-worker) 4 | 5 | Service Worker test repository. This is a very simple demo to show basic service worker features in action. 6 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Community Participation Guidelines 2 | 3 | This repository is governed by Mozilla's code of conduct and etiquette guidelines. 4 | For more details, please read the 5 | [Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). 6 | 7 | ## How to Report 8 | For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page. 9 | 10 | 16 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/LICENSE: -------------------------------------------------------------------------------- 1 | CC0 1.0 Universal 2 | 3 | Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an "owner") of an original work of 8 | authorship and/or a database (each, a "Work"). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific 12 | works ("Commons") that the public can reliably and without fear of later 13 | claims of infringement build upon, modify, incorporate in other works, reuse 14 | and redistribute as freely as possible in any form whatsoever and for any 15 | purposes, including without limitation commercial purposes. These owners may 16 | contribute to the Commons to promote the ideal of a free culture and the 17 | further production of creative, cultural and scientific works, or to gain 18 | reputation or greater distribution for their Work in part through the use and 19 | efforts of others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation 22 | of additional consideration or compensation, the person associating CC0 with a 23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work 25 | and publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights ("Copyright and 31 | Related Rights"). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 34 | i. the right to reproduce, adapt, distribute, perform, display, communicate, 35 | and translate a Work; 36 | 37 | ii. moral rights retained by the original author(s) and/or performer(s); 38 | 39 | iii. publicity and privacy rights pertaining to a person's image or likeness 40 | depicted in a Work; 41 | 42 | iv. rights protecting against unfair competition in regards to a Work, 43 | subject to the limitations in paragraph 4(a), below; 44 | 45 | v. rights protecting the extraction, dissemination, use and reuse of data in 46 | a Work; 47 | 48 | vi. database rights (such as those arising under Directive 96/9/EC of the 49 | European Parliament and of the Council of 11 March 1996 on the legal 50 | protection of databases, and under any national implementation thereof, 51 | including any amended or successor version of such directive); and 52 | 53 | vii. other similar, equivalent or corresponding rights throughout the world 54 | based on applicable law or treaty, and any national implementations thereof. 55 | 56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright 59 | and Related Rights and associated claims and causes of action, whether now 60 | known or unknown (including existing as well as future claims and causes of 61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 62 | duration provided by applicable law or treaty (including future time 63 | extensions), (iii) in any current or future medium and for any number of 64 | copies, and (iv) for any purpose whatsoever, including without limitation 65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes 66 | the Waiver for the benefit of each member of the public at large and to the 67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver 68 | shall not be subject to revocation, rescission, cancellation, termination, or 69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work 70 | by the public as contemplated by Affirmer's express Statement of Purpose. 71 | 72 | 3. Public License Fallback. Should any part of the Waiver for any reason be 73 | judged legally invalid or ineffective under applicable law, then the Waiver 74 | shall be preserved to the maximum extent permitted taking into account 75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver 76 | is so judged Affirmer hereby grants to each affected person a royalty-free, 77 | non transferable, non sublicensable, non exclusive, irrevocable and 78 | unconditional license to exercise Affirmer's Copyright and Related Rights in 79 | the Work (i) in all territories worldwide, (ii) for the maximum duration 80 | provided by applicable law or treaty (including future time extensions), (iii) 81 | in any current or future medium and for any number of copies, and (iv) for any 82 | purpose whatsoever, including without limitation commercial, advertising or 83 | promotional purposes (the "License"). The License shall be deemed effective as 84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the 85 | License for any reason be judged legally invalid or ineffective under 86 | applicable law, such partial invalidity or ineffectiveness shall not 87 | invalidate the remainder of the License, and in such case Affirmer hereby 88 | affirms that he or she will not (i) exercise any of his or her remaining 89 | Copyright and Related Rights in the Work or (ii) assert any associated claims 90 | and causes of action with respect to the Work, in either case contrary to 91 | Affirmer's express Statement of Purpose. 92 | 93 | 4. Limitations and Disclaimers. 94 | 95 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 96 | surrendered, licensed or otherwise affected by this document. 97 | 98 | b. Affirmer offers the Work as-is and makes no representations or warranties 99 | of any kind concerning the Work, express, implied, statutory or otherwise, 100 | including without limitation warranties of title, merchantability, fitness 101 | for a particular purpose, non infringement, or the absence of latent or 102 | other defects, accuracy, or the present or absence of errors, whether or not 103 | discoverable, all to the greatest extent permissible under applicable law. 104 | 105 | c. Affirmer disclaims responsibility for clearing rights of other persons 106 | that may apply to the Work or any use thereof, including without limitation 107 | any person's Copyright and Related Rights in the Work. Further, Affirmer 108 | disclaims responsibility for obtaining any necessary consents, permissions 109 | or other rights required for any use of the Work. 110 | 111 | d. Affirmer understands and acknowledges that Creative Commons is not a 112 | party to this document and has no duty or obligation with respect to this 113 | CC0 or use of the Work. 114 | 115 | For more information, please see 116 | 117 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/README.md: -------------------------------------------------------------------------------- 1 | # sw-test 2 | 3 | Service Worker test repository. This is a very simple demo to show basic service worker features in action. The demo can be seen on [our GitHub pages](https://mdn.github.io/sw-test/). 4 | 5 | You can find a lot more out about how this works by reading [Using Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers). 6 | In particular, read [Why is my service worker failing to register?](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Why_is_my_service_worker_failing_to_register) 7 | if you are having problems getting your code to do anything. You need to change the paths relative to where you are serving your files from! 8 | 9 | # Running locally 10 | 11 | To get this code. running locally on your computer as-is, you need to do the following: 12 | 13 | 1. Clone the repo in a location on your machine. 14 | 2. Start a local server running in the parent directory of the sw-test directory. For example, if you have Python on your machine you could start a server running on port 8001 using `python -m SimpleHTTPServer 8001` for Python 2.x, or `python3 -m http.server 8001` for Python 3.x. 15 | 3. Navigate to the sw-test directory on the local server, e.g. [http://localhost:8001/sw-test/](http://localhost:8001/sw-test/) 16 | 17 | Note: The example has to be located under the sw-test directory (e.g. http://localhost:8001/sw-test/) and not at the root of the server (e.g. http://localhost:8001/) or anywhere else, for the service worker to work. It expects the document and associated assets it is controlling to be at this location. 18 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/app.js: -------------------------------------------------------------------------------- 1 | import { Gallery } from './image-list.js'; 2 | 3 | const registerServiceWorker = async () => { 4 | if ('serviceWorker' in navigator) { 5 | try { 6 | const registration = await navigator.serviceWorker.register( 7 | '/sw-test/sw.js', 8 | { 9 | scope: '/sw-test/', 10 | } 11 | ); 12 | if (registration.installing) { 13 | console.log('Service worker installing'); 14 | } else if (registration.waiting) { 15 | console.log('Service worker installed'); 16 | } else if (registration.active) { 17 | console.log('Service worker active'); 18 | } 19 | } catch (error) { 20 | console.error(`Registration failed with ${error}`); 21 | } 22 | } 23 | }; 24 | 25 | const imgSection = document.querySelector('section'); 26 | 27 | const getImageBlob = async (url) => { 28 | const imageResponse = await fetch(url); 29 | if (!imageResponse.ok) { 30 | throw new Error( 31 | `Image didn't load successfully; error code: ${ 32 | imageResponse.statusText || imageResponse.status 33 | }` 34 | ); 35 | } 36 | return imageResponse.blob(); 37 | }; 38 | 39 | const createGalleryFigure = async (galleryImage) => { 40 | try { 41 | const imageBlob = await getImageBlob(galleryImage.url); 42 | const myImage = document.createElement('img'); 43 | const myCaption = document.createElement('caption'); 44 | const myFigure = document.createElement('figure'); 45 | myCaption.textContent = `${galleryImage.name}: Taken by ${galleryImage.credit}`; 46 | myImage.src = window.URL.createObjectURL(imageBlob); 47 | myImage.setAttribute('alt', galleryImage.alt); 48 | myFigure.append(myImage, myCaption); 49 | imgSection.append(myFigure); 50 | } catch (error) { 51 | console.error(error); 52 | } 53 | }; 54 | 55 | registerServiceWorker(); 56 | Gallery.images.map(createGalleryFigure); 57 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/gallery/bountyHunters.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdn/sw-test/d541d27dd9ae02e36b8eadee36b9a01e98409d94/service-worker/simple-service-worker/gallery/bountyHunters.jpg -------------------------------------------------------------------------------- /service-worker/simple-service-worker/gallery/myLittleVader.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdn/sw-test/d541d27dd9ae02e36b8eadee36b9a01e98409d94/service-worker/simple-service-worker/gallery/myLittleVader.jpg -------------------------------------------------------------------------------- /service-worker/simple-service-worker/gallery/snowTroopers.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdn/sw-test/d541d27dd9ae02e36b8eadee36b9a01e98409d94/service-worker/simple-service-worker/gallery/snowTroopers.jpg -------------------------------------------------------------------------------- /service-worker/simple-service-worker/image-list.js: -------------------------------------------------------------------------------- 1 | export const Path = 'gallery/'; 2 | 3 | export const Gallery = { 4 | images: [ 5 | { 6 | name: 'Darth Vader', 7 | alt: 'A Black Clad warrior lego toy', 8 | url: 'gallery/myLittleVader.jpg', 9 | credit: 10 | 'legOfenris, published under a Attribution-NonCommercial-NoDerivs 2.0 Generic license.', 11 | }, 12 | 13 | { 14 | name: 'Snow Troopers', 15 | alt: 'Two lego solders in white outfits walking across an icy plain', 16 | url: 'gallery/snowTroopers.jpg', 17 | credit: 18 | 'legOfenris, published under a Attribution-NonCommercial-NoDerivs 2.0 Generic license.', 19 | }, 20 | 21 | { 22 | name: 'Bounty Hunters', 23 | alt: 'A group of bounty hunters meeting, aliens and humans in costumes.', 24 | url: 'gallery/bountyHunters.jpg', 25 | credit: 26 | 'legOfenris, published under a Attribution-NonCommercial-NoDerivs 2.0 Generic license.', 27 | }, 28 | ], 29 | }; 30 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Service worker demo 9 | 10 | 11 | 14 | 15 | 16 | 17 |

Lego Star Wars gallery

18 | 19 |
20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/star-wars-logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdn/sw-test/d541d27dd9ae02e36b8eadee36b9a01e98409d94/service-worker/simple-service-worker/star-wars-logo.jpg -------------------------------------------------------------------------------- /service-worker/simple-service-worker/style.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | margin: 0; 4 | padding: 0; 5 | font-size: 10px; 6 | font-family: sans-serif; 7 | } 8 | 9 | h1 { 10 | text-indent: 100%; 11 | white-space: nowrap; 12 | overflow: hidden; 13 | height: 197px; 14 | background: url(star-wars-logo.jpg) no-repeat center; 15 | } 16 | 17 | section { 18 | max-width: 640px; 19 | margin: 0 auto; 20 | } 21 | 22 | figure { 23 | width: 100%; 24 | margin: 0; 25 | } 26 | 27 | img { 28 | width: 100%; 29 | box-shadow: 2px 2px 1px black; 30 | } 31 | 32 | caption { 33 | display: block; 34 | margin: 0 auto 1rem; 35 | width: 70%; 36 | font-size: 1.2rem; 37 | line-height: 1.5; 38 | padding: 5px; 39 | background: #ccc; 40 | box-shadow: 1px 1px 1px black; 41 | } 42 | -------------------------------------------------------------------------------- /service-worker/simple-service-worker/sw.js: -------------------------------------------------------------------------------- 1 | const addResourcesToCache = async (resources) => { 2 | const cache = await caches.open('v1'); 3 | await cache.addAll(resources); 4 | }; 5 | 6 | const putInCache = async (request, response) => { 7 | const cache = await caches.open('v1'); 8 | await cache.put(request, response); 9 | }; 10 | 11 | const cacheFirst = async ({ request, preloadResponsePromise, fallbackUrl }) => { 12 | // First try to get the resource from the cache 13 | const responseFromCache = await caches.match(request); 14 | if (responseFromCache) { 15 | return responseFromCache; 16 | } 17 | 18 | // Next try to use the preloaded response, if it's there 19 | const preloadResponse = await preloadResponsePromise; 20 | if (preloadResponse) { 21 | console.info('using preload response', preloadResponse); 22 | putInCache(request, preloadResponse.clone()); 23 | return preloadResponse; 24 | } 25 | 26 | // Next try to get the resource from the network 27 | try { 28 | const responseFromNetwork = await fetch(request); 29 | // response may be used only once 30 | // we need to save clone to put one copy in cache 31 | // and serve second one 32 | putInCache(request, responseFromNetwork.clone()); 33 | return responseFromNetwork; 34 | } catch (error) { 35 | const fallbackResponse = await caches.match(fallbackUrl); 36 | if (fallbackResponse) { 37 | return fallbackResponse; 38 | } 39 | // when even the fallback response is not available, 40 | // there is nothing we can do, but we must always 41 | // return a Response object 42 | return new Response('Network error happened', { 43 | status: 408, 44 | headers: { 'Content-Type': 'text/plain' }, 45 | }); 46 | } 47 | }; 48 | 49 | const enableNavigationPreload = async () => { 50 | if (self.registration.navigationPreload) { 51 | // Enable navigation preloads! 52 | await self.registration.navigationPreload.enable(); 53 | } 54 | }; 55 | 56 | self.addEventListener('activate', (event) => { 57 | event.waitUntil(enableNavigationPreload()); 58 | }); 59 | 60 | self.addEventListener('install', (event) => { 61 | event.waitUntil( 62 | addResourcesToCache([ 63 | '/sw-test/', 64 | '/sw-test/index.html', 65 | '/sw-test/style.css', 66 | '/sw-test/app.js', 67 | '/sw-test/image-list.js', 68 | '/sw-test/star-wars-logo.jpg', 69 | '/sw-test/gallery/bountyHunters.jpg', 70 | '/sw-test/gallery/myLittleVader.jpg', 71 | '/sw-test/gallery/snowTroopers.jpg', 72 | ]) 73 | ); 74 | }); 75 | 76 | self.addEventListener('fetch', (event) => { 77 | event.respondWith( 78 | cacheFirst({ 79 | request: event.request, 80 | preloadResponsePromise: event.preloadResponse, 81 | fallbackUrl: '/sw-test/gallery/myLittleVader.jpg', 82 | }) 83 | ); 84 | }); 85 | --------------------------------------------------------------------------------