Skip to content

Instantly share code, notes, and snippets.

View luke-denton-aligent's full-sized avatar
⌨️
Writing code for humans

Luke Denton luke-denton-aligent

⌨️
Writing code for humans
  • Aligent Consulting
  • Adelaide, Australia
View GitHub Profile
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
if (!navigator.serviceWorker) return; //Feature detection
navigator.serviceWorker.register("/sw.js").then(function() { //Include the service worker js file
//Registration worked
}).catch(function() {
//Registration didn't work
});
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
self.addEventListener('fetch', function(event) {
//Tell the browser that we're going to handle this request ourselves
//Takes a response object or a Promise, that resolves to a Response
event.respondWith(
new Response('Hello <strong class="a-winner-is-me">world</strong>', { //String is an example, this isn't the only option here
headers: {'Content-Type', 'text-html'} //Need to set the content type to make sure the HTML in the string is parsed
});
);
@luke-denton-aligent
luke-denton-aligent / create-new-request.js
Last active November 16, 2016 04:02
This snippet shows how to create a new request to another resource
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
fetch('/imgs/superman.jpg'); //Returns a Response object
//Example of it in use
//Using https://gist.github.com/luke-denton/4f2e9caf3ee95b84c692871f070d75df
self.addEventListener('fetch', function(event) {
event.respondWith(
//Any request made will receive a superman jpg as a response
fetch('/imgs/superman.jpg');
@luke-denton-aligent
luke-denton-aligent / selective-custom-request.js
Last active November 16, 2016 04:02
This snippet will show how to send a custom response to some requests, not all
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//Using example from https://gist.github.com/luke-denton/2d0f00e76151d9e4bf412df8eb1bf354
// This example will replace all jpgs with superman.jpg
self.addEventListener('fetch', function(event) {
if (event.request.url.endsWith('.jpg')) {
event.respondWith(
//Any request made will receive a superman jpg as a response
fetch('/imgs/superman.jpg');
);
@luke-denton-aligent
luke-denton-aligent / hijack-request-custom-response.js
Last active November 16, 2016 04:02
This snippet shows how to make a network call as normal, but before sending it to the browser, inspecting it and performing another action
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
self.addEventListener('fetch', function(event) {
event.respondWith(
//Make the request call as the browser would normally
fetch(event.request).then(function(reponse) {
//Check if the status is a 404, returning a custom response if true
if (response.status === 404) {
return new Response("Whoops, not found!");
}
@luke-denton-aligent
luke-denton-aligent / caching-assets.js
Last active November 16, 2016 04:02
This snippet shows how to cache website assets
// 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
self.addEventListener('install', function(event) {
var urlsToCache = [
'/',
'js.main.js',
'css/main.css',
@luke-denton-aligent
luke-denton-aligent / serving-cached-assets.js
Last active November 16, 2016 04:01
This snippet shows how to serve a cached file instead of having to load it from the network
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//Following on from previous example here: https://gist.github.com/luke-denton/ef791e5150470814a7a155cd85b1bf80
self.addEventListener('fetch', function(event) {
event.respondWith(
//Look for a match to the current request in all caches, resolves to a Promise
caches.match(event.request).then(function(response) {
//If the repsonse is truthy, meaning something was found in the cache, then return it
if (response) return response;
@luke-denton-aligent
luke-denton-aligent / updating-cached-files.js
Last active November 16, 2016 04:01
This snippet shows how to update files that have been cached
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//To trigger a new service worker to be created, the service worker code needs to be updated. This could be as simple
//as adding a comment to the file or, as we're doing here, increasing the cache version from 1 to 2, meaning there
//are likely new elements that need to be cached
var staticCacheName = "my-cache-v2";
//Fires when a service worker becomes active. Means its install has completed and it is now controlling the page
//Cache cleanup has to happen in the activate event because other service workers could still be using an old cache
//whilst the new service worker is spinning up. If the old cache is removed, that old service worker will no longer be
@luke-denton-aligent
luke-denton-aligent / notify-user-of-update.js
Last active July 26, 2019 15:55
This snippet shows how to notify the user of a new version of the site (a new service worker version)
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//This code is to be placed in a controller file, not in the service worker itself
IndexController.prototype._registerServiceWorker = function() {
if (!navigator.serviceWorker) return; //Feature detection
var indexController = this;
navigator.serviceWorker.register('/sw.js').then(function(reg) {
// If there's no controller, this page wasn't loaded via a service worker, so they're looking at the latest version.
@luke-denton-aligent
luke-denton-aligent / triggering-update.js
Last active September 17, 2022 23:28
This snippet shows how to trigger an update for a service worker, so it is not waiting for the old service worker to stop controlling a page
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//Using the example from https://gist.github.com/luke-denton/e52cff8e13fc4efa0f9d83d7729304d1
IndexController.prototype._registerServiceWorker = function() {
// ... (see https://gist.github.com/luke-denton/e52cff8e13fc4efa0f9d83d7729304d1 for the rest of this function body
//Listen for the controllerchange event, which will mean a new service worker has taken control
navigator.serviceWorker.addEventListener('controllerchange', function() {
window.location.reload();