Skip to content

Instantly share code, notes, and snippets.

@inian
Last active June 11, 2019 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inian/217d28218401ff6a6582b58956c83d2e to your computer and use it in GitHub Desktop.
Save inian/217d28218401ff6a6582b58956c83d2e to your computer and use it in GitHub Desktop.
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