Last active
June 11, 2019 18:15
-
-
Save inian/217d28218401ff6a6582b58956c83d2e to your computer and use it in GitHub Desktop.
Network aware asset optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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