Skip to content

Instantly share code, notes, and snippets.

@jeffposnick
jeffposnick / package.json
Created March 24, 2021 19:43
workbox-webpack-plugin example
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack"
},
"keywords": [],
"author": "",
@jeffposnick
jeffposnick / fallback-on-error-plugin.js
Last active January 4, 2021 12:13
Example Workbox plugin that fallsback to a cached HTML page when there's a non-200 OK navigation response.
export class FallbackOnErrorPlugin {
constructor(fallbackURL) {
this.fallbackURL = fallbackURL;
}
// This is called whenever there's a network response,
// but we want special behavior for non-2xx statuses.
fetchDidSucceed({response}) {
if (response.ok) {
// If it's a 2xx, it can be used as-is.
import {RouteHandlerCallbackOptions} from 'workbox-core/types';
import {CacheFirst, NetworkFirst} from 'workbox-strategies';
import {registerRoute} from 'workbox-routing';
// Borrowed from https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook#cache-and-network-race
function promiseAny(promises: Array<Promise<Response>>): Promise<Response> {
return new Promise((resolve, reject) => {
promises = promises.map(p => Promise.resolve(p));
promises.forEach(p => p.then(resolve));
promises.reduce((a, b) => a.catch(() => b))
@jeffposnick
jeffposnick / totalCacheSize.js
Created October 11, 2019 19:12
Snippet to get the total size of everything in the Cache Storage API for the current origin
async function totalCacheSize() {
let size = 0;
const cacheNames = await caches.keys();
for (const cacheName of cacheNames) {
const cache = await caches.open(cacheName);
const cachedRequests = await cache.keys();
for (const cachedRequest of cachedRequests) {
const cachedResponse = await cache.match(cachedRequest);
const responseBlob = await cachedResponse.blob();
size += responseBlob.size;
@jeffposnick
jeffposnick / new-service-worker.ts
Created October 6, 2019 16:54
Workbox CDN + JS service worker migrated to a custom bundle + TS equivalent
import {CacheFirst, NetworkOnly} from 'workbox-strategies';
import {cacheNames} from 'workbox-core';
import {cleanupOutdatedCaches, getCacheKeyForURL, precacheAndRoute} from 'workbox-precaching';
import {ExpirationPlugin} from 'workbox-expiration';
import {initialize as initializeOfflineAnalytics} from 'workbox-google-analytics';
import {registerRoute, setCatchHandler} from 'workbox-routing';
import {RouteHandlerCallbackOptions} from 'workbox-core/types';
import {skipWaiting} from 'workbox-core';
import nunjucks from 'nunjucks/browser/nunjucks';
@jeffposnick
jeffposnick / custom-wb-code.js
Created September 27, 2019 13:53
Example of using importScriptsViaChunks
import {registerRoute} from 'workbox-routing/registerRoute';
registerRoute('/path', yourHandlerCode);
@jeffposnick
jeffposnick / service-worker.js
Created September 20, 2019 00:56
Example of InjectManifest in Workbox v5
// Add any other logic here as needed.
import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin';
import { CacheFirst } from 'workbox-strategies/CacheFirst';
import { createHandlerForURL } from 'workbox-precaching/createHandlerForURL';
import { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin';
import { NavigationRoute } from 'workbox-routing/NavigationRoute';
import { precacheAndRoute } from 'workbox-precaching/precacheAndRoute';
import { registerRoute } from 'workbox-routing/registerRoute';
addEventListener('install', (event) => ; {
event.waitUntil(async function() {
const cache = await caches.open('static-v1');
await cache.addAll(['offline.html', 'styles.css']);
}());
});
// See https://developers.google.com/web/updates/2017/02/navigation-preload#activating_navigation_preload
addEventListener('activate', event => {
event.waitUntil(async function() {
@jeffposnick
jeffposnick / camino.sh
Created December 19, 2018 15:17
Shell script to automate nightly updates for the Camino browser (circa 2003?)
#!/bin/sh
echo "Beginning Camino Nightly Download: `date`" >> /Users/jeff/Documents/Camino/log.txt
echo "Changing to download folder" >> /Users/jeff/Documents/Camino/log.txt
cd ~/Documents/Camino
echo "pwd is: `pwd`" >> /Users/jeff/Documents/Camino/log.txt
echo "Downloading Camino: `date`" >> /Users/jeff/Documents/Camino/log.txt
@jeffposnick
jeffposnick / find-opaque-responses.js
Created December 2, 2018 17:39
Code to find all opaque responses currently cached, and return their URLs.
async function findOpaqueResponses() {
const cacheNames = await caches.keys();
const urlsResultingInAnOpaqueResponse = [];
for (const cacheName of cacheNames) {
const cache = await caches.open(cacheName);
const requests = await cache.keys();
for (const request of requests) {
const response = await cache.match(request);
if (response.status === 0) {
urlsResultingInAnOpaqueResponse.push(request.url);