Browse Source

Add service worker and cache assets

pm2
Luke Childs 8 years ago
parent
commit
892c761c7e
  1. 6
      public/assets/enhancements.js
  2. 48
      public/sw.js

6
public/assets/enhancements.js

@ -54,6 +54,7 @@
div.innerHTML = '<svg/>';
return 'classList' in div.firstChild;
})(),
serviceWorker: 'serviceWorker' in navigator
}
};
@ -222,6 +223,11 @@
}
};
// Register service worker
if(supports.test(['serviceWorker'])) {
navigator.serviceWorker.register('/sw.js');
}
// Init favourite nodes
if(supports.test(['localStorage', 'inlineSVG', 'querySelector', 'classList'])) {
favouriteNodes.init();

48
public/sw.js

@ -0,0 +1,48 @@
var cacheName = 'top-explorer-cache-v1';
// Install
self.addEventListener('install', function(event) {
// Cache assets
event.waitUntil(
caches.open(cacheName)
.then(function(cache) {
return cache.addAll([
'/assets/style.css',
'/assets/enhancements.js',
'/assets/iconfont.woff',
'/assets/heart.svg'
]);
})
);
});
// Fetch
self.addEventListener('fetch', function(event) {
var requestUrl = new URL(event.request.url);
// Only do stuff with our own urls
if(requestUrl.origin !== location.origin) {
return;
}
// Always check cache for assets
if(requestUrl.pathname.startsWith('/assets/')) {
checkCacheFirst(event);
return;
}
});
// Try cache first, if we don't have it make the request
function checkCacheFirst(event) {
return event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response;
}
return fetch(event.request);
}
)
);
}
Loading…
Cancel
Save