summaryrefslogtreecommitdiff
path: root/worker.js
blob: 88a97c411e48fc8f847bfec92b28b1a15cc02005 (plain)
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
//importScripts('lib/localforage.min.js');

var CACHE_NAME = 'epube-v1';

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME).then(function(cache) {
		var urls = [
			'read.html',
			'js/common.js',
			'js/read.js',
			'js/offline.js',
			'css/read.css',
			'css/index.css',
			'offline.html',
			'lib/zip.min.js',
			'lib/epub.js',
			'lib/localforage.min.js',
			'lib/holder.min.js',
			'lib/smartimages.js',
			'lib/bootstrap/v3/css/bootstrap-theme.min.css',
			'lib/bootstrap/v3/css/bootstrap.min.css',
			'lib/bootstrap/v3/js/jquery.js',
			'lib/bootstrap/v3/js/bootstrap.min.js',
			'lib/bootstrap/v3/fonts/glyphicons-halflings-regular.woff2',
		];

		return cache.addAll(urls.map(url => new Request(url, {credentials: 'same-origin'})));
    })
  );
});

this.addEventListener('fetch', function(event) {
	var req = event.request.clone();

	if (req.method != "GET") return;

	event.respondWith(
		caches.match(req).then(function(resp) {

			if (!navigator.onLine) {
				if (resp) return resp;

				if (req.url.match("read.html")) {
					return caches.match("read.html");
				}

				if (req.url.match("index.php")) {
					return caches.match("offline.html");
				}

				return;
			}

			//console.log("<<<", req.url);

			// refresh cached files
			return caches.open(CACHE_NAME).then(function(cache) {
				return fetch(req.url,{credentials: 'include'}).then(function(resp) {
					return caches.match(req).then(function(match) {
						if (match) cache.put(req.url, resp.clone());
						return resp;
					});
				});
			});
		})
	);

});