I can not register a service worker. The file is located along with the index.js and app.js. I get next errors
A bad HTTP response code (404) was received when fetching the script.
Failed to load resource: net::ERR_INVALID_RESPONSE
Registration failed TypeError: Failed to register a ServiceWorker: A
bad HTTP response code (404) was received when fetching the script.
******
if ('serviceWorker' in navigator) {
window.addEventListener('`load`', () => {
navigator.serviceWorker.register('serviceWorker.js', { scope:'./' })
.then((registration) => {
console.log('Registration completed successfully',registration);
})
.catch((error) => {
console.log('Registration failed', error);
})
})}
It not only have to be along side index.js and app.js, it has to be in the root of your application. so if it happens your index.js or app.js are in a folder say js, it wont work. just put serviceWorker.js in the same directory as index.html and please run it in a server
Why is this? I am not an expert at this, but I know service workers are used to serve all your files on an offline scenerio. If you put it as a relative path, it's going to be tricky to map to all other files outside.
This is not a rule though, you can somehow find a way to put your serviceWorker in some subfolder, but I personally don't consider this a best practice
Service Workers are used to cache assets and other files so that in case of slow network or the user being offline results could be rendered on the screen. This results in better user experience.
For details you might want to visit:- https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
This is done at the index.js and if you are using latest CRA version you just need to modify the last line from serviceWorker.unregister();
to serviceWorker.register();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With