Added service worker and site caching
This commit is contained in:
parent
c416354cfa
commit
96f7f8462b
@ -1,5 +1,6 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import ReactDOM from "react-dom";
|
import ReactDOM from "react-dom";
|
||||||
|
import * as ServiceWorker from "./registerServiceWorker";
|
||||||
|
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
@ -12,3 +13,4 @@ ReactDOM.render(
|
|||||||
document.getElementById("root")
|
document.getElementById("root")
|
||||||
);
|
);
|
||||||
|
|
||||||
|
ServiceWorker.register();
|
||||||
|
16
src/registerServiceWorker.ts
Normal file
16
src/registerServiceWorker.ts
Normal 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))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
22
src/serviceWorker/cache.ts
Normal file
22
src/serviceWorker/cache.ts
Normal 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);
|
||||||
|
}
|
||||||
|
};
|
10
src/serviceWorker/index.ts
Normal file
10
src/serviceWorker/index.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { precache } from "./cache";
|
||||||
|
|
||||||
|
declare const self: ServiceWorkerGlobalScope;
|
||||||
|
|
||||||
|
self.addEventListener("install", (event) => {
|
||||||
|
self.skipWaiting();
|
||||||
|
event.waitUntil(precache());
|
||||||
|
});
|
||||||
|
|
||||||
|
export type {};
|
Loading…
x
Reference in New Issue
Block a user