Skip to content

Instantly share code, notes, and snippets.

@inian inian/brotli-sw.js
Last active Jan 23, 2019

Embed
What would you like to do?
Enabling Brotli on CDNs which don't support it yet
// MIT License
// Copyright (c) 2016 Dexecure
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
var db;
// return true if this is a text asset which can be Brotli compressed (like JS / CSS)
function isTextAsset(url) {
return /(\.js|\.css)$/.test(url);
}
// return true if this is a domain you control
function isFirstPartyDomain(url) {
return new URL(url).hostname === "example.com";
}
// Singleton class to return an Indexed Database instance
function getIDB() {
return new Promise((resolve, reject) => {
if (db) {
// returning the existing IDB instance
resolve(db);
} else {
var request = indexedDB.open("Dexecure", 1);
request.onerror = function (event) {
reject(request.error);
};
request.onsuccess = function (event) {
db = request.result;
resolve(request.result);
};
}
});
}
// read from IDB and get Brotli status
function getBrotliStatus() {
return getIDB()
.then((db) => {
return new Promise((resolve, reject) => {
var transaction = db.transaction("config");
var objectStore = transaction.objectStore("config");
var request = objectStore.get(1);
request.onerror = function (event) {
// safely asssume brotli not supported
reject(false);
};
request.onsuccess = function (event) {
resolve(event.target.result.isBrotliSupported);
};
});
})
}
self.addEventListener('install', (event) => {
event.waitUntil(
fetch('https://blog.dexecure.com/content/images/perm/test.br')
.then((res) => {
if (res.ok) {
return res.text();
}
})
.then((resp) => {
// check if the browser was able to decode the Brotli response correctly
var isBrotliSupported = (resp === 'Dexecure');
return isBrotliSupported;
})
.catch(() => {
// assume brotli is not supported if request fails to be safe
var isBrotliSupported = false;
return isBrotliSupported;
})
.then((isBrotliSupported) => {
// save Brotli Support status into IndexedDB
return new Promise((resolve, reject) => {
var request = indexedDB.open("Dexecure", 1);
request.onerror = function (event) {
reject(request.error);
};
request.onsuccess = function (event) {
db = request.result;
var transaction = db.transaction("config", "readwrite");
var store = transaction.objectStore("config");
var config = {
isBrotliSupported: isBrotliSupported
}
var request2 = store.put(config, 1);
request2.onsuccess = function () {
resolve();
}
};
request.onupgradeneeded = function (e) {
var thisDB = e.target.result;
if (!thisDB.objectStoreNames.contains("config")) {
thisDB.createObjectStore("config");
}
}
});
})
.then(() => self.skipWaiting())
);
});
self.addEventListener('fetch', function (event) {
var url = event.request.url;
// send a custom header to your server announcing Brotli support for future requests
if (isTextAsset(url) && isFirstPartyDomain(url)) {
event
.respondWith(
getBrotliStatus()
.then((isBrotliSupported) => {
var headersToSend = new Headers({});
if (isBrotliSupported) {
headersToSend = new Headers({
'brotli-supported': 'true'
});
}
return fetch(url, {
mode: 'cors',
headers: headersToSend
})
.then(response => {
if (response.ok) {
return response;
} else {
throw new Error('Unable to fetch optimised image');
}
})
.catch(err => fetch(event.request))
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.