From 9708b1c12eeea2454ebf429ec9bfb28c564b37eb Mon Sep 17 00:00:00 2001 From: tdro Date: Mon, 15 Jan 2024 19:06:28 -0500 Subject: static/js/pager: Avoid stacking load listeners --- assets/js/index.js | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) (limited to 'assets') diff --git a/assets/js/index.js b/assets/js/index.js index 491cf59..5bbcd1a 100644 --- a/assets/js/index.js +++ b/assets/js/index.js @@ -13,20 +13,21 @@ const link = function() { url = self.location.href.split("#")[0].split("?")[0]; }; - const scrollRestore = function(url) { - if (history.scrollRestoration) history.scrollRestoration = "manual"; - pager = JSON.parse(localStorage[key]); + const scrollHash = function(url, load = false) { const hash = self.location.hash; const fragment = hash.slice(1) && document.getElementById(hash.slice(1)); - const fragmentInURL = hash.length > 0; - if (fragmentInURL && document.body.contains(fragment)) { - pager[url] = self.pageYOffset; - localStorage[key] = JSON.stringify(pager); - fragment.scrollIntoView(); - return self.addEventListener("DOMContentLoaded", function() { - fragment.scrollIntoView(); - }); + const fragmented = hash.length > 0; + const hashed = fragmented && document.body.contains(fragment); + if (hashed) { + self.location.hash = hash; + if (load) fragment.scrollIntoView(); } + return hashed; + }; + const scrollRestore = function(url) { + if (history.scrollRestoration) history.scrollRestoration = "manual"; + if (scrollHash(url)) return; + pager = JSON.parse(localStorage[key]); if (pager[url] > 0) { clearInterval(seek); self.scrollTo(0, pager[url]); @@ -60,12 +61,9 @@ history.go(-1); } }; - self.addEventListener("DOMContentLoaded", function() { - self.addEventListener("click", function(event) { - const up = document.getElementById("top"); - const back = document.getElementById("back"); - scrollReverse(back, up, event); - }); + self.addEventListener("load", function() { + link(); + scrollHash(url, true); }); [ "DOMContentLoaded", @@ -77,6 +75,13 @@ if (event.type === "pageshow") { return event.persisted && self.scrollTo(0, pager[url]); } + if (event.type === "DOMContentLoaded") { + self.addEventListener("click", function(event) { + const up = document.getElementById("top"); + const back = document.getElementById("back"); + scrollReverse(back, up, event); + }); + } link(); scrollRestore(url); }); -- cgit v1.2.3