From 457b9f2b1f9b13cccf55c2e9afb12f586769242a Mon Sep 17 00:00:00 2001 From: Pagwin Date: Fri, 18 Apr 2025 19:48:58 -0400 Subject: [PATCH] added script for a live reload setup, may develop further in future --- static/js/simple-live-reload.mjs | 45 ++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 static/js/simple-live-reload.mjs diff --git a/static/js/simple-live-reload.mjs b/static/js/simple-live-reload.mjs new file mode 100644 index 0000000..915cae1 --- /dev/null +++ b/static/js/simple-live-reload.mjs @@ -0,0 +1,45 @@ +"use strict"; + +// CREDIT: https://leanrada.com/notes/simple-live-reload +// ACHIVE: https://web.archive.org/web/20250418234708/https://leanrada.com/notes/simple-live-reload/ + +let watching = new Set(); +watch(location.href); + +new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + watch(entry.name); + } +}).observe({ type: "resource", buffered: true }); + +function watch(urlString) { + if (!urlString) return; + const url = new URL(urlString); + if (url.origin !== location.origin) return; + + if (watching.has(url.pathname)) return; + watching.add(url.pathname); + + console.log("watching", url.pathname); + + let lastModified, etag; + + async function check() { + const res = await fetch(url, { method: "head" }); + const newLastModified = res.headers.get("Last-Modified"); + const newETag = res.headers.get("ETag"); + + if ( + (lastModified !== undefined || etag !== undefined) && + (lastModified !== newLastModified || etag !== newETag) + ) { + location.reload(); + } + + lastModified = newLastModified; + etag = newETag; + } + + setInterval(check, 1000); +} +