1/* =========================================================== 2 * sw.js 3 * =========================================================== 4 * Copyright 2016 @huxpro 5 * Licensed under Apache 2.0 6 * Register service worker. 7 * ========================================================== */ 8 9const PRECACHE = 'precache-v1'; 10const RUNTIME = 'runtime'; 11const HOSTNAME_WHITELIST = [ 12 self.location.hostname, 13 "huangxuan.me", 14 "yanshuo.io", 15 "cdnjs.cloudflare.com" 16] 17 18 19// The Util Function to hack URLs of intercepted requests 20const getFixedUrl = (req) => { 21 var now = Date.now(); 22 url = new URL(req.url) 23 24 // 1. fixed http URL 25 // Just keep syncing with location.protocol 26 // fetch(httpURL) belongs to active mixed content. 27 // And fetch(httpRequest) is not supported yet. 28 url.protocol = self.location.protocol 29 30 // 2. add query for caching-busting. 31 // Github Pages served with Cache-Control: max-age=600 32 // max-age on mutable content is error-prone, with SW life of bugs can even extend. 33 // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string. 34 // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190 35 url.search += (url.search ? '&' : '?') + 'cache-bust=' + now; 36 return url.href 37} 38 39// The Util Function to detect and polyfill req.mode="navigate" 40// request.mode of 'navigate' is unfortunately not supported in Chrome 41// versions older than 49, so we need to include a less precise fallback, 42// which checks for a GET request with an Accept: text/html header. 43const isNavigationReq = (req) => (req.mode === 'navigate' || (req.method === 'GET' && req.headers.get('accept').includes('text/html'))) 44 45// The Util Function to detect if a req is end with extension 46// Accordin to Fetch API spec <https://fetch.spec.whatwg.org/#concept-request-destination> 47// Any HTML's navigation has consistently mode="navigate" type="" and destination="document" 48// including requesting an img (or any static resources) from URL Bar directly. 49// So It ends up with that regExp is still the king of URL routing ;) 50// P.S. An url.pathname has no '.' can not indicate it ends with extension (e.g. /api/version/1.2/) 51const endWithExtension = (req) => Boolean(new URL(req.url).pathname.match(/\.\w+$/)) 52 53// Redirect in SW manually fixed github pages arbitray 404s on things?blah 54// what we want: 55// repo?blah -> !(gh 404) -> sw 302 -> repo/?blah 56// .ext?blah -> !(sw 302 -> .ext/?blah -> gh 404) -> .ext?blah 57// If It's a navigation req and it's url.pathname isn't end with '/' or '.ext' 58// it should be a dir/repo request and need to be fixed (a.k.a be redirected) 59// Tracking https://twitter.com/Huxpro/status/798816417097224193 60const shouldRedirect = (req) => (isNavigationReq(req) && new URL(req.url).pathname.substr(-1) !== "/" && !endWithExtension(req)) 61 62// The Util Function to get redirect URL 63// `${url}/` would mis-add "/" in the end of query, so we use URL object. 64// P.P.S. Always trust url.pathname instead of the whole url string. 65const getRedirectUrl = (req) => { 66 url = new URL(req.url) 67 url.pathname += "/" 68 return url.href 69} 70 71/** 72 * @Lifecycle Install 73 * Precache anything static to this version of your app. 74 * e.g. App Shell, 404, JS/CSS dependencies... 75 * 76 * waitUntil() : installing ====> installed 77 * skipWaiting() : waiting(installed) ====> activating 78 */ 79self.addEventListener('install', e => { 80 e.waitUntil( 81 caches.open(PRECACHE).then(cache => { 82 return cache.add('offline.html') 83 .then(self.skipWaiting()) 84 .catch(err => console.log(err)) 85 }) 86 ) 87}); 88 89 90/** 91 * @Lifecycle Activate 92 * New one activated when old isnt being used. 93 * 94 * waitUntil(): activating ====> activated 95 */ 96self.addEventListener('activate', event => { 97 console.log('service worker activated.') 98 event.waitUntil(self.clients.claim()); 99}); 100 101 102/** 103 * @Functional Fetch 104 * All network requests are being intercepted here. 105 * 106 * void respondWith(Promise<Response> r); 107 */ 108self.addEventListener('fetch', event => { 109 // logs for debugging 110 console.log(`fetch ${event.request.url}`) 111 //console.log(` - type: ${event.request.type}; destination: ${event.request.destination}`) 112 //console.log(` - mode: ${event.request.mode}, accept: ${event.request.headers.get('accept')}`) 113 114 // Skip some of cross-origin requests, like those for Google Analytics. 115 if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) { 116 117 // Redirect in SW manually fixed github pages 404s on repo?blah 118 if(shouldRedirect(event.request)){ 119 event.respondWith(Response.redirect(getRedirectUrl(event.request))) 120 return; 121 } 122 123 // Stale-while-revalidate 124 // similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale 125 // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
126 const cached = caches.match(event.request); 127 const fixedUrl = getFixedUrl(event.request); 128 const fetched = fetch(fixedUrl, {cache: "no-store"}); 129 const fetchedCopy = fetched.then(resp => resp.clone()); 130 131 // Call respondWith() with whatever we get first. 132 // If the fetch fails (e.g disconnected), wait for the cache. 133 // If thereâs nothing in cache, wait for the fetch. 134 // If neither yields a response, return offline pages. 135 event.respondWith( 136 Promise.race([fetched.catch(_ => cached), cached]) 137 .then(resp => resp || fetched) 138 .catch(_ => caches.match('offline.html')) 139 ); 140 141 // Update the cache with the version we fetched (only for ok status) 142 event.waitUntil( 143 Promise.all([fetchedCopy, caches.open(RUNTIME)]) 144 .then(([response, cache]) => response.ok && cache.put(event.request, response)) 145 .catch(_ => {/* eat any errors */}) 146 ); 147 } 148});
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.