1 | initial version |
There are a few steps you can take to ensure that your create-react-app will reload when the service worker is updated:
// serviceWorker.js
register(null, {
skipWaiting: false,
clientsClaim: false,
});
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
// Wait for service worker to register
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js').then(registration => {
console.log('Service worker registered:', registration);
// Force reload when new service worker becomes active
registration.addEventListener('updatefound', () => {
console.log('New service worker found!');
// If a new service worker is found, wait until it becomes active, then reload the page
registration.installing!.addEventListener('statechange', () => {
if (registration.waiting) {
// Perform the reload
window.location.reload();
}
});
});
}).catch(error => {
console.log('Service worker registration failed:', error);
});
});
}
This listener will wait for the service worker to register and then listen for any updates. When a new service worker is found, it will wait until it becomes active and then reload the page.
// serviceWorker.js
register(null);
This will ensure that the service worker is activated as soon as it is updated, without any additional prompting.