Skip to content

Instantly share code, notes, and snippets.

@Antoinebr
Last active February 25, 2018 11:20
Show Gist options
  • Save Antoinebr/72e01c7df9b074caa0d34b3099941dc9 to your computer and use it in GitHub Desktop.
Save Antoinebr/72e01c7df9b074caa0d34b3099941dc9 to your computer and use it in GitHub Desktop.

Why my serviceworker doesn't refresh ?

Try closing the tab and reopening it, or just navigating to a different site and then hitting the back button. This should allow the old service worker to become redundant, your new one to activate, and the background to finally change to red.

By adding a version number to our cache, and incrementing it every time one of our files change we achieve two goals:

  1. Any change to the service worker file, even one as minuscule as changing a single digit in the cache version number, lets the browser know it is time to install a new service worker to replace the active one. This triggers a new install event, causing the new files to be downloaded and stored in the cache.

  2. It creates a separate cache for each version of our service worker. This is important because even though we already updated the cache, until the user has closed all open pages, the old service worker is still the active one. That service worker may expect certain files to be in the cache, files that may have been changed by the newer service worker. By letting each service worker have its own cache, we can make sure there are no unexpected surprises.

list caches

List the cache :

caches.keys().then(function(cacheNames) {

    cacheNames.forEach(function(cacheName) {
        //caches.delete(cacheName);
        console.log('cache => ', cacheName);
    });

});

Cache list can also be accesible in Chrome dev tool : Application -> Cache

var CACHE_NAME = "gih-cache";
var CACHED_URLS = [
"/index-offline.html",
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
"/css/gih-offline.css",
"/img/jumbo-background-sm.jpg",
"/img/logo-header.png"
];
self.addEventListener("install", function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) { // we open or create the cache
return cache.addAll(CACHED_URLS); // we put all urls contained in CACHED_URL in the cache
})
);
});
self.addEventListener("fetch", function(event) {
event.respondWith(
fetch(event.request).catch(function() { // if the fetch fail
return caches.match(event.request).then(function(response) {
if (response) { // match will allways resolve() we have to check for the response
return response;
}
// if there's no response and the request is "text/html" we return index-offline.html
else if (event.request.headers.get("accept").includes("text/html") ){
return caches.match("/index-offline.html");
}
});
})
);
});
function listCaches(){
return new Promise( (resolve, reject) => {  
   
caches.keys().then(function(cacheNames) {
if( cacheNames.length === 0 ) return reject("no caches");
return resolve(cacheNames);
});
})
}
function getCachedRequest(cacheName){
return new Promise( (resolve, reject) => {  
caches.open(cacheName).then(function(cache) {
if( cache.length === 0 ) return reject("no caches");
cache.keys().then( keyList => {
return resolve(keyList);
});
});
})
}
/* USE */
listCaches().then( c => console.log(c) ).catch( c => console.log(c) );
getCachedUrls("sw-precache-v3-my-vue-app-https://todo.antoinebrossault.com/").then(e => console.log(e) );
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/serviceworker.js").then(function(registration){
console.log("Service Worker registered with scope:", registration.scope );
}).catch(function(err) {
console.log("Service worker registration failed:", err);
});
}
self.addEventListener("fetch", function(event) {
console.log("Fetch request for:", event.request.url);
});
/*
| --------------------------------------------------------------------------
| Intercept request and respond with something else
| --------------------------------------------------------------------------
| Here if bootrap.min.css is requested we respond with a custom CSS
|
self.addEventListener("fetch", function(event) {
if (event.request.url.includes("bootstrap.min.css")) {
event.respondWith(
new Response( ".hotel-slogan {background: green!important;} nav {display:none}",
{ headers: { "Content-Type": "text/css" }}
)
);
}
});
*/
/*
| --------------------------------------------------------------------------
| We can listen an image request and replace it
| --------------------------------------------------------------------------
|
*/
self.addEventListener("fetch", function(event) {
if (event.request.url.includes("/img/logo.png")) {
event.respondWith(
fetch("/img/logo-flipped.png")
);
}
});
/*
| --------------------------------------------------------------------------
| Fetch return a promise : so we can catch if something goes wrong
| --------------------------------------------------------------------------
|
| In this example : if the request can't be made we awnser with a text response
|
*/
var responseContent = "<html>" +
"<body>" +
"<style>" +
"body {text-align: center; background-color: #333; color: #eee;}"+
"</style>" +
"<h1>Gotham Imperial Hotel</h1>" +
"<p>There seems to be a problem with your connection.</p>" +
"<p>Come visit us at 1 Imperial Plaza, Gotham City for free WiFi.</p>"+
"</body>" +
"</html>";
self.addEventListener("fetch", function(event) {
event.respondWith(
fetch(event.request).catch(function() {
return new Response(responseContent, { headers: { "Content-Type": "text/html; charset=utf-8" }}
);
})
);
});
/*
| --------------------------------------------------------------------------
| Delete all old caches
| --------------------------------------------------------------------------
|
*/
self.addEventListener("activate", function(event) { // Listen for the activate event.
event.waitUntil( // Wait until the following is done and only declare the service worker activated
caches.keys().then(function(cacheNames) {
return Promise.all( // if all of the following complete successfully:
cacheNames.map(function(cacheName) { // For each of the cache names:
console.log('cache ', cacheName );
if ( CACHE_NAME !== cacheName && cacheName.startsWith("gih-cache") ) { // Check if a cache's name is not the same as the current cache name and its name starts with 'gih-cache':
return caches.delete(cacheName); // Delete that cache.
}
})
);
})
);
});
/*
| --------------------------------------------------------------------------
| Network first and cache if fail
| --------------------------------------------------------------------------
|
*/
self.addEventListener("fetch", function(event) {
if( event.request.includes('jsonplaceholder.typicode.com')){
console.log(event.request, '🔥');
event.respondWith(
fetch(event.request).catch(function() {
return caches.match(event.request);
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment