Last active
February 13, 2018 11:17
-
-
Save benfoxall/921c69a127c068e0387fac98a617fea7 to your computer and use it in GitHub Desktop.
A script that runs in 5 places
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
if(typeof document !== 'undefined') { | |
// normal script tag | |
console.log("Hello #1") | |
navigator.serviceWorker.register( | |
document.currentScript.src | |
) | |
} else { | |
// running as a service worker | |
console.log("Hello #2") | |
self.addEventListener('fetch', e => { | |
const {url, headers} = e.request | |
if(url != self.location.href) return | |
e.respondWith( | |
headers.get('accept').includes('text/html') | |
// HTML served by visiting /script.js directly | |
? new Response( | |
'<h1>Hello #3', | |
{headers: {'Content-Type': 'text/html'}} | |
) | |
// JS served by including script.js with a tag | |
: new Response((_ => `(${_})()`)(() => { | |
console.log("Hello #4") | |
window.reset = () => | |
navigator.serviceWorker.getRegistrations() | |
.then(rs => rs.forEach(r => r.unregister())) | |
}), | |
{headers: { 'Content-Type': 'application/javascript' }} | |
) | |
) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment