Skip to content

Instantly share code, notes, and snippets.

@udhaya21
Last active July 3, 2023 05:48
Show Gist options
  • Save udhaya21/851e4a95f3cc5ef081267eba12a9bdf6 to your computer and use it in GitHub Desktop.
Save udhaya21/851e4a95f3cc5ef081267eba12a9bdf6 to your computer and use it in GitHub Desktop.
React + Service worker - Offline support
import { createRoot } from 'react-dom/client';
import * as serviceWorker from './service-worker';
const root = createRoot(document.getElementById('root'));
root.render(<h1>Hello, world</h1>);
serviceWorker.register();
export function register(config) {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
registerValidSW(swUrl, config);
});
}
}
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function (response) {
return response || fetch(event.request);
})
);
});
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl, { scope: '/' })
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
console.log('Content is cached for offline use.');
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment