anbot

c1d80cc / feed-live.js

View file at this commit

diff --git a/feed-live.js b/feed-live.js
new file mode 100644
index 0000000..70be57d
--- /dev/null
+++ b/feed-live.js
@@ -0,0 +1,30 @@
+const entries = document.getElementById('feed-entries')
+let refreshing = false
+
+async function refreshFeed() {
+  if (document.hidden || refreshing) return
+  refreshing = true
+  try {
+    const response = await fetch(window.location.href, {
+      cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(10000)
+    })
+    if (!response.ok) return
+    const nextPage = new DOMParser().parseFromString(await response.text(), 'text/html')
+    const nextEntries = nextPage.getElementById('feed-entries')
+    if (!nextEntries || nextEntries.innerHTML === entries.innerHTML) return
+
+    const focusedLink = entries.contains(document.activeElement) ? document.activeElement.href : null
+    entries.replaceChildren(...nextEntries.childNodes)
+    if (focusedLink) {
+      const link = Array.from(entries.querySelectorAll('a')).find(item => item.href === focusedLink)
+      link?.focus({ preventScroll: true })
+    }
+  } catch {
+    // Keep the current entries during a connection failure. The next poll retries.
+  } finally {
+    refreshing = false
+  }
+}
+
+setInterval(refreshFeed, 3000)
+document.addEventListener('visibilitychange', refreshFeed)

Git ยท Social feed