Created
June 14, 2018 02:26
-
-
Save marutypes/e6735f9ed5ce28dab29fb086f1274d03 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const isLocalhost = Boolean( | |
window.location.hostname === 'localhost' || | |
// [::1] is the IPv6 localhost address. | |
window.location.hostname === '[::1]' || | |
// 127.0.0.1/8 is considered localhost for IPv4. | |
window.location.hostname.match( | |
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ | |
) | |
); | |
export default function register() { | |
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { | |
const publicUrl = new URL(process.env.PUBLIC_URL, window.location); | |
if (publicUrl.origin !== window.location.origin) { | |
return; | |
} | |
window.addEventListener('load', () => { | |
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; | |
if (isLocalhost) { | |
checkValidServiceWorker(swUrl); | |
navigator.serviceWorker.ready.then(() => { | |
console.log( | |
'This web app is being served cache-first by a service ' + | |
'worker. To learn more, visit https://goo.gl/SC7cgQ' | |
); | |
}); | |
} else { | |
registerValidSW(swUrl); | |
} | |
}); | |
} | |
} | |
function registerValidSW(swUrl) { | |
navigator.serviceWorker | |
.register(swUrl) | |
.then(registration => { | |
registration.onupdatefound = () => { | |
const installingWorker = registration.installing; | |
installingWorker.onstatechange = () => { | |
if (installingWorker.state === 'installed') { | |
if (navigator.serviceWorker.controller) { | |
console.log('New content is available; please refresh.'); | |
} else { | |
console.log('Content is cached for offline use.'); | |
} | |
} | |
}; | |
}; | |
}) | |
.catch(error => { | |
console.error('Error during service worker registration:', error); | |
}); | |
} | |
function checkValidServiceWorker(swUrl) { | |
fetch(swUrl) | |
.then(response => { | |
if ( | |
response.status === 404 || | |
response.headers.get('content-type').indexOf('javascript') === -1 | |
) { | |
navigator.serviceWorker.ready.then(registration => { | |
registration.unregister().then(() => { | |
window.location.reload(); | |
}); | |
}); | |
} else { | |
registerValidSW(swUrl); | |
} | |
}) | |
.catch(() => { | |
console.log( | |
'No internet connection found. App is running in offline mode.' | |
); | |
}); | |
} | |
export function unregister() { | |
if ('serviceWorker' in navigator) { | |
navigator.serviceWorker.ready.then(registration => { | |
registration.unregister(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment