caching improvements

Signed-off-by: ari melody <ari@arimelody.me>
This commit is contained in:
ari melody 2024-04-17 17:08:53 +01:00
parent c5a2491627
commit 0b401c058a
4 changed files with 94 additions and 55 deletions

View file

@ -1,21 +1,31 @@
const swap_event = new Event("swap");
let caches = {};
window.lmao = caches;
async function check_cache(url) {
if (caches[url]) {
return caches[url];
} else {
const res = await fetch(url);
async function cached_fetch(url) {
let cached = caches[url];
console.log("cache: " + cached);
if (res.status !== 200) return;
if (!res.headers.get("content-type").startsWith("text/html")) return;
const res = cached === undefined ? await fetch(url) : await fetch(url, {
headers: {
"If-Modified-Since": cached.last_modified
}
});
const text = await res.text();
caches[url] = text;
return text;
if (res.status === 304 && cached !== undefined) {
return cached.content;
}
if (res.status !== 200) return;
if (!res.headers.get("content-type").startsWith("text/html")) return;
const text = await res.text();
if (res.headers.get("last-modified")) {
caches[url] = {
content: text,
last_modified: res.headers.get("last-modified")
}
}
return text;
}
async function swap(url, stateful) {
@ -29,7 +39,7 @@ async function swap(url, stateful) {
if (stateful && window.location.href.endsWith(url)) return;
const text = await check_cache(url);
const text = await cached_fetch(url);
const content = new DOMParser().parseFromString(text, "text/html");
const stylesheets = [...content.querySelectorAll("link[rel='stylesheet']")];