Last active
August 29, 2015 14:03
-
-
Save phamann/d1da851731fa790d6e2c to your computer and use it in GitHub Desktop.
Simple ServiceWorker for Guardian hackday
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log("Worker startup"); | |
this.oninstall = function(event) { | |
console.log('Worker install'); | |
event.waitUntil( | |
caches.create('static').then(function(cache) { | |
return cache.add( | |
//Templates | |
'/assets/offline/offline-list.html', | |
//Assets | |
'/assets/images/global/sprite.png', | |
'/assets/stylesheets/head.default.css', | |
'/assets/stylesheets/global.css' | |
); | |
}).catch(function(err){ | |
console.log('Worker install failed'); | |
console.log(err); | |
}) | |
); | |
}; | |
this.onactivate = function(event) { | |
console.log("Worker activate"); | |
console.log('worker caches:', caches); | |
}; | |
this.addEventListener('fetch', function(event) { | |
console.log('fetch:', event.request.url); | |
console.log('network state:', navigator.connection.type); | |
//If agent is offline | |
if(navigator.connection.type === "none") { | |
//If request is a static asset get from cache | |
if(/^\/assets\//.test(event.request.url)){ | |
return caches.match(event.request).catch(function() { | |
event.default(); | |
}); | |
} | |
//All others return fallback template | |
return caches.match('/assets/offline/offline-list.html'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I managed to get the cache semi working without the polyfill using this:
But will look into the polyfill now as you suggest. Was also slightly confused why the isServiceWorkerReady page had no yellow light yet the
caches
object was still available. But understandable seeing as the spec is still changing.I've been meaning to play with it all and get my head around it for the last couple of months, so very happy to be finally do it. So yes playing with TweetDeck too will be fun.
I'll let you know how I get on, and will video the final result.