Added service worker and site caching

This commit is contained in:
Dmitriy Shishkov 2021-07-31 21:21:45 +03:00
parent c416354cfa
commit 96f7f8462b
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
4 changed files with 50 additions and 0 deletions

View File

@ -1,5 +1,6 @@
import React from "react";
import ReactDOM from "react-dom";
import * as ServiceWorker from "./registerServiceWorker";
import "./index.css";
@ -12,3 +13,4 @@ ReactDOM.render(
document.getElementById("root")
);
ServiceWorker.register();

View File

@ -0,0 +1,16 @@
export const register = () => {
if ("serviceWorker" in navigator) {
window.addEventListener("load", () =>
navigator.serviceWorker
.register("/sw.js")
.then((registration) => {
if (process.env.NODE_ENV === "development")
console.log(
"Successfully registered ServiceWorker with scope:",
registration.scope
);
})
.catch((err) => console.error(err))
);
}
};

View File

@ -0,0 +1,22 @@
import { CACHE } from "../constants";
const getCache = () => caches.open(CACHE);
/**
* Caches static files for application
*/
export const precache = async () =>
(await getCache()).addAll(["/", "/index.js", "/sw.js"]);
/**
* Requests file from network or gets it from cache if offline
*/
export const fromCache = async (request: Request) => {
try {
const response = await fetch(request);
(await getCache()).put(request, response);
return response;
} catch (err) {
return (await getCache()).match(request);
}
};

View File

@ -0,0 +1,10 @@
import { precache } from "./cache";
declare const self: ServiceWorkerGlobalScope;
self.addEventListener("install", (event) => {
self.skipWaiting();
event.waitUntil(precache());
});
export type {};