Skip to content

Commit 2dad062

Browse files
committed
build sw.js
1 parent 178bd68 commit 2dad062

2 files changed

Lines changed: 323 additions & 1 deletion

File tree

‎index.html‎

Lines changed: 129 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,129 @@
1-
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><title>CODELF</title><meta name="description" content="Best GitHub stars, repositories tagger and organizer. Search over projects from Github, Bitbucket, Google Code, Codeplex, Sourceforge, Fedora Project, GitLab to find real-world usage variable names."><meta name="keywords" content="Codelf,变量命名,函数命名,方法命名,变量命名神器,GitHub 分组,Organize GitHub stars,naming things,naming convention,programming naming"><meta http-equiv="x-ua-compatible" content="ie=edge"><link rel="shortcut icon" href="images/codelf_logo.f4ae25bd.png"><link rel="apple-touch-icon" sizes="144x144" href="images/codelf_logo.f4ae25bd.png"><link rel="apple-touch-icon-precomposed" href="images/codelf_logo.f4ae25bd.png"><link title="CODELF" type="application/opensearchdescription+xml" rel="search" href="./opensearch.xml"><link type="text/css" rel="stylesheet" href="./css/lib.365f8ae0.css"><link type="text/css" rel="stylesheet" href="./css/app.79a153d0.css"><script src="js/lib.2ef380a5.js"></script></head><body ontouchstart><div class="app"></div><script src="./js/app.f0f29d58.js"></script></body></html>
1+
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><title>CODELF</title><meta name="description" content="Best GitHub stars, repositories tagger and organizer. Search over projects from Github, Bitbucket, Google Code, Codeplex, Sourceforge, Fedora Project, GitLab to find real-world usage variable names."><meta name="keywords" content="Codelf,变量命名,函数命名,方法命名,变量命名神器,GitHub 分组,Organize GitHub stars,naming things,naming convention,programming naming"><meta http-equiv="x-ua-compatible" content="ie=edge"><link rel="shortcut icon" href="images/codelf_logo.f4ae25bd.png"><link rel="apple-touch-icon" sizes="144x144" href="images/codelf_logo.f4ae25bd.png"><link rel="apple-touch-icon-precomposed" href="images/codelf_logo.f4ae25bd.png"><link title="CODELF" type="application/opensearchdescription+xml" rel="search" href="./opensearch.xml"><link type="text/css" rel="stylesheet" href="./css/lib.365f8ae0.css"><link type="text/css" rel="stylesheet" href="./css/app.79a153d0.css"><script src="js/lib.2ef380a5.js"></script></head><body ontouchstart><div class="app"></div><script src="./js/app.f0f29d58.js"></script><script>if (/https/.test(location.protocol) && 'serviceWorker' in navigator) {
2+
if (!Cache.prototype.add) {
3+
Cache.prototype.add = function add(request) {
4+
return this.addAll([request]);
5+
};
6+
}
7+
8+
if (!Cache.prototype.addAll) {
9+
Cache.prototype.addAll = function addAll(requests) {
10+
var cache = this;
11+
12+
// Since DOMExceptions are not constructable:
13+
function NetworkError(message) {
14+
this.name = 'NetworkError';
15+
this.code = 19;
16+
this.message = message;
17+
}
18+
NetworkError.prototype = Object.create(Error.prototype);
19+
20+
return Promise.resolve().then(function() {
21+
if (arguments.length < 1) throw new TypeError();
22+
23+
// Simulate sequence<(Request or USVString)> binding:
24+
var sequence = [];
25+
26+
requests = requests.map(function(request) {
27+
if (request instanceof Request) {
28+
return request;
29+
}
30+
else {
31+
return String(request); // may throw TypeError
32+
}
33+
});
34+
35+
return Promise.all(
36+
requests.map(function(request) {
37+
if (typeof request === 'string') {
38+
request = new Request(request);
39+
}
40+
41+
var scheme = new URL(request.url).protocol;
42+
43+
if (scheme !== 'http:' && scheme !== 'https:') {
44+
throw new NetworkError("Invalid scheme");
45+
}
46+
47+
return fetch(request.clone());
48+
})
49+
);
50+
}).then(function(responses) {
51+
// TODO: check that requests don't overwrite one another
52+
// (don't think this is possible to polyfill due to opaque responses)
53+
return Promise.all(
54+
responses.map(function(response, i) {
55+
return cache.put(requests[i], response);
56+
})
57+
);
58+
}).then(function() {
59+
return undefined;
60+
});
61+
};
62+
}
63+
64+
if (!CacheStorage.prototype.match) {
65+
// This is probably vulnerable to race conditions (removing caches etc)
66+
CacheStorage.prototype.match = function match(request, opts) {
67+
var caches = this;
68+
69+
return this.keys().then(function(cacheNames) {
70+
var match;
71+
72+
return cacheNames.reduce(function(chain, cacheName) {
73+
return chain.then(function() {
74+
return match || caches.open(cacheName).then(function(cache) {
75+
return cache.match(request, opts);
76+
}).then(function(response) {
77+
match = response;
78+
return match;
79+
});
80+
});
81+
}, Promise.resolve());
82+
});
83+
};
84+
}
85+
86+
if ('serviceWorker' in navigator) {
87+
// Delay registration until after the page has loaded, to ensure that our
88+
// precaching requests don't degrade the first visit experience.
89+
// See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration
90+
window.addEventListener('load', function() {
91+
// Your service-worker.js *must* be located at the top-level directory relative to your site.
92+
// It won't be able to control pages unless it's located at the same level or higher than them.
93+
// *Don't* register service worker file in, e.g., a scripts/ sub-directory!
94+
// See https://github.com/slightlyoff/ServiceWorker/issues/468
95+
navigator.serviceWorker.register('sw.js').then(function(reg) {
96+
// updatefound is fired if service-worker.js changes.
97+
reg.onupdatefound = function() {
98+
// The updatefound event implies that reg.installing is set; see
99+
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
100+
var installingWorker = reg.installing;
101+
102+
installingWorker.onstatechange = function() {
103+
switch (installingWorker.state) {
104+
case 'installed':
105+
if (navigator.serviceWorker.controller) {
106+
// At this point, the old content will have been purged and the fresh content will
107+
// have been added to the cache.
108+
// It's the perfect time to display a "New content is available; please refresh."
109+
// message in the page's interface.
110+
console.log('New or updated content is available.');
111+
} else {
112+
// At this point, everything has been precached.
113+
// It's the perfect time to display a "Content is cached for offline use." message.
114+
console.log('Content is now available offline!');
115+
}
116+
break;
117+
118+
case 'redundant':
119+
console.error('The installing service worker became redundant.');
120+
break;
121+
}
122+
};
123+
};
124+
}).catch(function(e) {
125+
console.error('Error during service worker registration:', e);
126+
});
127+
});
128+
}
129+
}</script></body></html>

‎sw.js‎

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
/*
2+
Copyright 2014 Google Inc. All Rights Reserved.
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
14+
// While overkill for this specific sample in which there is only one cache,
15+
// this is one best practice that can be followed in general to keep track of
16+
// multiple caches used by a given service worker, and keep them all versioned.
17+
// It maps a shorthand identifier for a cache to a specific, versioned cache name.
18+
19+
// Note that since global state is discarded in between service worker restarts, these
20+
// variables will be reinitialized each time the service worker handles an event, and you
21+
// should not attempt to change their values inside an event handler. (Treat them as constants.)
22+
23+
// If at any point you want to force pages that use this service worker to start using a fresh
24+
// cache, then increment the CACHE_VERSION value. It will kick off the service worker update
25+
// flow and the old cache(s) will be purged as part of the activate event handler when the
26+
// updated service worker is activated.
27+
var CACHE_VERSION = 20181227122100;
28+
var CURRENT_CACHES = {
29+
prefetch: 'prefetch-cache-v' + CACHE_VERSION
30+
};
31+
32+
self.addEventListener('install', function(event) {
33+
var now = Date.now();
34+
35+
var urlsToPrefetch = ["./",
36+
"css/app.79a153d0.css",
37+
"css/app.css",
38+
"css/lib.365f8ae0.css",
39+
"css/lib.css",
40+
"css/styles.css",
41+
"css/styles.d06dda8f.css",
42+
"fonts/Dressedless_Three.svg",
43+
"fonts/Dressedless_Three.ttf",
44+
"fonts/FontAwesome.otf",
45+
"fonts/LatoLatin-Bold.woff2",
46+
"fonts/LatoLatin-BoldItalic.woff2",
47+
"fonts/LatoLatin-Italic.woff2",
48+
"fonts/LatoLatin-Regular.woff2",
49+
"fonts/fontawesome-webfont.eot",
50+
"fonts/fontawesome-webfont.svg",
51+
"fonts/fontawesome-webfont.ttf",
52+
"fonts/fontawesome-webfont.woff",
53+
"fonts/fontawesome-webfont.woff2",
54+
"images/404_dribbble.ae94d03c.gif",
55+
"images/404_dribbble.gif",
56+
"images/codelf_logo.f4ae25bd.png",
57+
"images/codelf_logo.png",
58+
"images/paypal.69412e83.png",
59+
"images/paypal.png",
60+
"images/twohardtings.0db8462a.jpg",
61+
"images/twohardtings.jpg",
62+
"images/wechatpay.48ba089d.jpg",
63+
"images/wechatpay.jpg",
64+
"images/zhifubao.70c19370.png",
65+
"images/zhifubao.png",
66+
"js/app.f0f29d58.js",
67+
"js/app.js",
68+
"js/app.js.map",
69+
"js/lib.2ef380a5.js",
70+
"js/lib.js",
71+
"css/themes/default/assets/fonts/brand-icons.eot",
72+
"css/themes/default/assets/fonts/brand-icons.svg",
73+
"css/themes/default/assets/fonts/brand-icons.ttf",
74+
"css/themes/default/assets/fonts/brand-icons.woff",
75+
"css/themes/default/assets/fonts/brand-icons.woff2",
76+
"css/themes/default/assets/fonts/icons.eot",
77+
"css/themes/default/assets/fonts/icons.otf",
78+
"css/themes/default/assets/fonts/icons.svg",
79+
"css/themes/default/assets/fonts/icons.ttf",
80+
"css/themes/default/assets/fonts/icons.woff",
81+
"css/themes/default/assets/fonts/icons.woff2",
82+
"css/themes/default/assets/fonts/outline-icons.eot",
83+
"css/themes/default/assets/fonts/outline-icons.svg",
84+
"css/themes/default/assets/fonts/outline-icons.ttf",
85+
"css/themes/default/assets/fonts/outline-icons.woff",
86+
"css/themes/default/assets/fonts/outline-icons.woff2",
87+
"css/themes/default/assets/images/flags.png"];
88+
89+
// All of these logging statements should be visible via the "Inspect" interface
90+
// for the relevant SW accessed via chrome://serviceworker-internals
91+
console.log('Handling install event. Resources to prefetch:', urlsToPrefetch);
92+
93+
event.waitUntil(
94+
caches.open(CURRENT_CACHES.prefetch).then(function(cache) {
95+
var cachePromises = urlsToPrefetch.map(function(urlToPrefetch) {
96+
// This constructs a new URL object using the service worker's script location as the base
97+
// for relative URLs.
98+
var url = new URL(urlToPrefetch, location.href);
99+
// Append a cache-bust=TIMESTAMP URL parameter to each URL's query string.
100+
// This is particularly important when precaching resources that are later used in the
101+
// fetch handler as responses directly, without consulting the network (i.e. cache-first).
102+
// If we were to get back a response from the HTTP browser cache for this precaching request
103+
// then that stale response would be used indefinitely, or at least until the next time
104+
// the service worker script changes triggering the install flow.
105+
url.search += (url.search ? '&' : '?') + 'cache-bust=' + now;
106+
107+
// It's very important to use {mode: 'no-cors'} if there is any chance that
108+
// the resources being fetched are served off of a server that doesn't support
109+
// CORS (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
110+
// In this example, www.chromium.org doesn't support CORS, and the fetch()
111+
// would fail if the default mode of 'cors' was used for the fetch() request.
112+
// The drawback of hardcoding {mode: 'no-cors'} is that the response from all
113+
// cross-origin hosts will always be opaque
114+
// (https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cross-origin-resources)
115+
// and it is not possible to determine whether an opaque response represents a success or failure
116+
// (https://github.com/whatwg/fetch/issues/14).
117+
var request = new Request(url, {mode: 'no-cors'});
118+
return fetch(request).then(function(response) {
119+
if (response.status >= 400) {
120+
throw new Error('request for ' + urlToPrefetch +
121+
' failed with status ' + response.statusText);
122+
}
123+
124+
// Use the original URL without the cache-busting parameter as the key for cache.put().
125+
return cache.put(urlToPrefetch, response);
126+
}).catch(function(error) {
127+
console.error('Not caching ' + urlToPrefetch + ' due to ' + error);
128+
});
129+
});
130+
131+
return Promise.all(cachePromises).then(function() {
132+
console.log('Pre-fetching complete.');
133+
});
134+
}).catch(function(error) {
135+
console.error('Pre-fetching failed:', error);
136+
})
137+
);
138+
});
139+
140+
self.addEventListener('activate', function(event) {
141+
// Delete all caches that aren't named in CURRENT_CACHES.
142+
// While there is only one cache in this example, the same logic will handle the case where
143+
// there are multiple versioned caches.
144+
var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
145+
return CURRENT_CACHES[key];
146+
});
147+
148+
event.waitUntil(
149+
caches.keys().then(function(cacheNames) {
150+
return Promise.all(
151+
cacheNames.map(function(cacheName) {
152+
if (expectedCacheNames.indexOf(cacheName) === -1) {
153+
// If this cache name isn't present in the array of "expected" cache names, then delete it.
154+
console.log('Deleting out of date cache:', cacheName);
155+
return caches.delete(cacheName);
156+
}
157+
})
158+
);
159+
})
160+
);
161+
});
162+
163+
self.addEventListener('fetch', function(event) {
164+
console.log('Handling fetch event for', event.request.url);
165+
var requestURL = new URL(event.request.url);
166+
requestURL.origin == location.origin && event.respondWith(
167+
// caches.match() will look for a cache entry in all of the caches available to the service worker.
168+
// It's an alternative to first opening a specific named cache and then matching on that.
169+
caches.match(event.request).then(function(response) {
170+
if (response) {
171+
console.log('Found response in cache:', response);
172+
173+
return response;
174+
}
175+
176+
console.log('No response found in cache. About to fetch from network...');
177+
178+
// event.request will always have the proper mode set ('cors, 'no-cors', etc.) so we don't
179+
// have to hardcode 'no-cors' like we do when fetch()ing in the install handler.
180+
return fetch(event.request).then(function(response) {
181+
console.log('Response from network is:', response);
182+
183+
return response;
184+
}).catch(function(error) {
185+
// This catch() will handle exceptions thrown from the fetch() operation.
186+
// Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
187+
// It will return a normal response object that has the appropriate error code set.
188+
console.error('Fetching failed:', error);
189+
190+
throw error;
191+
});
192+
})
193+
);
194+
});

0 commit comments

Comments
 (0)