Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register service worker?

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);
            })
     })}
like image 425
J.Michael Avatar asked Aug 31 '25 10:08

J.Michael


2 Answers

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

like image 69
andylamax Avatar answered Sep 03 '25 03:09

andylamax


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();

like image 37
SAURABH Avatar answered Sep 03 '25 01:09

SAURABH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!