Skip to content

Commit a24c398

Browse files
committed
Update sw.js
Trim out some unneeded code. Fix a bug that caused serviceworker not to cache some pages.
1 parent 1782e06 commit a24c398

1 file changed

Lines changed: 8 additions & 17 deletions

File tree

sw.js

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ return self.clients.matchAll().then(clients => {
99

1010

1111
const cacheName = "beginner-javascript-tutorial"
12-
const waitOnFirstLoad = 0 //Milliseconds to wait before fetching items on preload list. Helps prevent duplicate requests on first load.
1312

1413
//Array of items to try and preload on install (the serviceWorker will install without them preloaded). Can be exact or relative to serviceWorker scope
1514
const preloadList = [
@@ -23,20 +22,17 @@ const preloadList = [
2322
"codemirror-5.42.0/mode/css/css.js"
2423
]
2524

26-
preloadList.concat(self.order)
2725

2826
function rebaseURL(url) {
2927
//Fills in relative URLs using the serviceWorker scope
3028
return (new URL(url, registration.scope)).href
3129
}
3230

31+
//Add pages in self.order to preloadList
32+
self.order.forEach(arr => {preloadList.push(arr[0])})
3333

34-
async function preload() {
35-
//Allow requests by the page to get into browser cache, so that we don't sent 2 requests for the same thing.
36-
await new Promise((resolve, reject) => {
37-
setTimeout(resolve, waitOnFirstLoad)
38-
})
3934

35+
async function preload() {
4036
const cache = await caches.open(cacheName)
4137
let requests = []
4238
for (let index in preloadList) {
@@ -55,14 +51,7 @@ async function preload() {
5551
}
5652
}
5753

58-
59-
function activateHandler(event) {
60-
event.waitUntil(preload())
61-
}
62-
63-
self.addEventListener("activate", activateHandler)
64-
65-
54+
//Make sure something has changed since the data was last cached.
6655
async function checkForChanges() {
6756
const cache = await caches.open(cacheName)
6857
let url = "https://api.github.com/repos/ecc521/beginner-javascript-tutorial/commits/master"
@@ -79,11 +68,13 @@ async function checkForChanges() {
7968

8069
if (hash !== oldHash) {
8170
console.log("Tutorial has changed since data was cached. Updating data in cache.")
82-
preload()
71+
await preload()
8372
}
8473
}
8574

86-
checkForChanges() //Not sure exactly when this runs. Should run occasionally though.
75+
checkForChanges() //Updates cache to the latest version.
76+
77+
8778

8879

8980
//Milliseconds to wait for network response before using cache

0 commit comments

Comments
 (0)