Skip to content

Instantly share code, notes, and snippets.

@scottdomes
Last active May 22, 2018 13:56
Show Gist options
  • Select an option

  • Save scottdomes/ff78cc64a9216e6d29d28d519c5c4e8d to your computer and use it in GitHub Desktop.

Select an option

Save scottdomes/ff78cc64a9216e6d29d28d519c5c4e8d to your computer and use it in GitHub Desktop.
// Set this to true for production
var doCache = false;
// Name our cache
var CACHE_NAME = 'my-pwa-cache-v1';
// Delete old caches that are not our current one!
self.addEventListener("activate", event => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keyList =>
Promise.all(keyList.map(key => {
if (!cacheWhitelist.includes(key)) {
console.log('Deleting cache: ' + key)
return caches.delete(key);
}
}))
)
);
});
// The first time the user starts up the PWA, 'install' is triggered.
self.addEventListener('install', function(event) {
if (doCache) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
// Get the assets manifest so we can see what our js file is named
// This is because webpack hashes it
fetch("asset-manifest.json")
.then(response => {
response.json()
})
.then(assets => {
// Open a cache and cache our files
// We want to cache the page and the main.js generated by webpack
// We could also cache any static assets like CSS or images
const urlsToCache = [
"/",
assets["main.js"]
]
cache.addAll(urlsToCache)
console.log('cached');
})
})
);
}
});
// When the webpage goes to fetch files, we intercept that request and serve up the matching files
// if we have them
self.addEventListener('fetch', function(event) {
if (doCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
});
@vieiralucas
Copy link

This is missing a return on line 33

You can also remove the curly braces

@vieiralucas
Copy link

Also thanks a lot for this! ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment