Skip to content

Instantly share code, notes, and snippets.

@inian

inian/network-aware-sw.js

Last active Jun 11, 2019
Embed
What would you like to do?
Network aware asset optimization
function modifyURL(url) {
// ect can be 'slow-2g', '2g', '3g', or '4g'.
const connectionType = navigator.connection.effectiveType;
if (connectionType === "slow-2g" || connectionType === "2g") {
return url + "?opt=aggressive";
} else if (connectionType === "4g") {
return url + "?opt=mild";
} else {
return url + "?opt=default";
}
}
self.addEventListener("fetch", async event => {
if (event.request.method != "GET") {
return;
}
if (event.request.destination != "image") {
return;
}
event.respondWith(fetch(modifyURL(event.request.url)));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment