-
Notifications
You must be signed in to change notification settings - Fork 0
/
swoff.js
140 lines (112 loc) · 3.3 KB
/
swoff.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/**
* swoff.js
* A Service Worker that provides offline usage by caching GET responses.
*
* @version 1.0.0
* @author Nim Jayawardena - Feel free to bother me with questions!
*/
const CACHE_NAME = 'my-app-1.0.1'; // Used for versioning your cache.
/**
* Only URL listed in URL_CACHE_INFO will be cached.
* Only GET requests will be cached.
*
* @typedef {Object} UrlCacheInfo
* @property {string} url
* @property {boolean} cacheAsap - If true, Swoff will cache as soon as possible.
*/
const URL_CACHE_INFO = [
{ url: '/', cacheAsap: true },
{ url: '/index.html', cacheAsap: true },
{ url: '/assets/script.js', cacheAsap: true },
{ url: '/assets/stylesheet.css', cacheAsap: true },
{ url: '/assets/script-not.js', cacheAsap: false },
{ url: '/assets/script-not-cached-asap.js', cacheAsap: false },
];
const LOG = true; // Disable/Enable console.log()s as you like.
function log(msg) {
if (LOG) {
console.log(`%cSwoff %c${msg}`, 'text-shadow: 0px 0px 5px #79dc64;', '');
}
}
function main() {
log('Running...');
self.addEventListener('install', (event) => {
log('Installing...');
cacheAsaps(event);
});
interceptFetches();
}
/**
* @param {string} relUrl - Something like "/path/to/file".
* @returns {string} - Something like "https://my-app.com/path/to/file"
*/
function relUrlToAbsUrl(relUrl) {
return location.origin + relUrl;
}
function getUrlCacheInfo(url) {
log(`getUrlCacheInfo(${url})`);
return URL_CACHE_INFO.find((urlInfo) => {
const absoluteUrl = relUrlToAbsUrl(urlInfo.url);
return absoluteUrl === url;
});
}
function cacheAsaps() {
return caches.open(CACHE_NAME).then((cache) => {
const urlsToCache = URL_CACHE_INFO
.filter(urlInfo => urlInfo.cacheAsap)
.map(urlInfo => urlInfo.url);
// TODO: See if there's a cleaner way to handle empty urlsToCache.
log(`Caching all of ${urlsToCache.join(', ')}.`);
return cache.addAll(urlsToCache);
});
}
function interceptFetches() {
self.addEventListener('fetch', (event) => {
log(`Intercepting fetch of ${event.request.url}`);
const interception = fetchFromNetwork(event.request)
.catch(() => fetchFromCache(event.request));
event.respondWith(interception);
});
}
function fetchFromNetwork(request) {
return new Promise((resolve, reject) => {
if (!navigator.onLine) {
log('We are offline.');
return reject();
}
const timeoutId = setTimeout(reject, 5000);
let fetchedResponse = null;
log(`Fetching from network ${request.url}.`);
fetch(request)
.then((response) => {
fetchedResponse = response;
clearTimeout(timeoutId);
return cacheUrl(request.url);
})
.then(() => resolve(fetchedResponse));
});
}
function fetchFromCache(request) {
log(`Fetching from cache: ${request.url}.`);
return caches.open(CACHE_NAME)
.then(cache => cache.match(request))
.then((matching) => {
if (!matching) { log(`Cache missed for ${request.url}.`); }
return matching || Promise.reject();
});
}
function cacheUrl(url) {
return caches.open(CACHE_NAME).then((cache) => {
const cacheInfo = getUrlCacheInfo(url);
if (cacheInfo) {
log(`Caching ${url}.`);
return cache.add(url);
}
log(`Not caching ${url}.`);
});
}
try {
main();
} catch (err) {
log('Failed to run.');
}