I am learning about PWAs and I am trying to apply my new knowledge about cache strategies on a React app, but despite I have changed the line at src/index.js to serviceWorker.register()
and this works, the recently created file public/service-worker.js is not being reached.
Just to try I have created a "custom register function" on src/serviceWorker.js :
export function customRegister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(process.env.PUBLIC_URL + '/service-worker.js')
.then(reg => {
reg.onupdatefound = () => {
const installation = reg.installing;
installation.onstatechange = () => {
if (installation.state === 'activated') {
console.log('%cActivated SW', 'font-size: 1.2rem; color: green; font-weight: bolder');
}
}
}
})
.catch(error => {
console.log('%cError while registering SW:', 'font-size: 1.2rem; color: red; font-weight: bolder');
console.log(error);
});
}
}
Despite the service worker is registered, this is the result when I change on src/index.js
to serviceWorker.customRegister()
:
But I just added these functions (one at time) and none of these works:
self.oninstall = () => {
console.log('SW install');
};
Or
self.addEventListener('install', () => {
console.log('SW install');
});
I have tried different codes but no luck. Any suggestions?
Not sure why, but even if I deleted the service-worker.js the serviceWorker.js registered the SW and no error was triggered.
The only way I found to properly register the SW was changing the SW name on serviceWorker.js :
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/sw.js`;
...
}
I guess this is the expected outcome since React service worker is made for Production as it says on this Github issue .
This was the function I made on src/sw-register.js :
export function LocalRegister() {
const swPath = `${process.env.PUBLIC_URL}/sw.js`;
if ('serviceWorker' in navigator) {
window.onload = () => {
navigator.serviceWorker.register(swPath)
.then(registration => {
registration.onupdatefound = () => {
const installation = registration.installing;
installation.onstatechange = () => {
if (installation.state === 'activated') {
console.log('%cSW Activated', 'font-size: 1.2rem; color: green; font-weight: bolder');
}
}
}
})
.catch(error => {
console.log('%cError while registering SW:', 'font-size: 1.2rem; color: red; font-weight: bolder');
console.log(error);
});
}
}
}
Then I just referred to this on src/index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
//import * as serviceWorker from './serviceWorker';
import * as serviceWorker from './sw-register';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.LocalRegister();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.