Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AhmedKorim/232bd269c4b4703bf5fefb3b911783d1 to your computer and use it in GitHub Desktop.
Save AhmedKorim/232bd269c4b4703bf5fefb3b911783d1 to your computer and use it in GitHub Desktop.
This snippet shows how to cache and serve a skeleton page
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//When a browser runs a service worker for the first time, an event is fired within it, 'install'. This can be used
//to trigger functions to download assets and save them to the cache, using the Cache API
//Started with snippet from https://gist.github.com/luke-denton/ef791e5150470814a7a155cd85b1bf80
var staticCacheName = "my-cache-v2"; //Update the cache version
self.addEventListener('install', function(event) {
var urlsToCache = [
'/skeleton', //Change this from / to /skeleton
'js.main.js',
'css/main.css',
'imgs/icon.png',
'https://fonts.gstatic.com/s/roboto/v15/2UX7WLTfW3W8TclTUvlFyQ.woff',
'https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff'
];
//call event.waitUntil with the same code as referenced snippet
});
self.addEventListener('fetch', function(event) {
//Respond to requests for the root page with the page skeleton from the cache
var requestUrl = new URL(event.request.url);
//Only intercept requests from the same origin (i.e. Don't intercept Google Fonts requests, or any third party request like that)
if (requestUrl.origin === location.origin) {
//Check if the request is for the root page
if (requestUrl.pathname === '/') {
//Respond with the cached skeleton, which will be there as it is now cached as part of the install step
event.respondWith(caches.match('/skeleton'));
return;
}
}
//Call respond with to handle requests that aren't from the same origin or for the root page
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment