Skip to content

Instantly share code, notes, and snippets.

@benfoxall
Last active February 13, 2018 11:17
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 benfoxall/921c69a127c068e0387fac98a617fea7 to your computer and use it in GitHub Desktop.
Save benfoxall/921c69a127c068e0387fac98a617fea7 to your computer and use it in GitHub Desktop.
A script that runs in 5 places
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