Forked from kartiknair/spa-navigation-for-static-links.js
Created
September 11, 2020 18:45
-
-
Save virajkulkarni14/80d8914bc158e5a315756e6660ad0d7b to your computer and use it in GitHub Desktop.
Revisions
-
kartiknair created this gist
Jun 21, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,48 @@ window.onload = function () { console.log("page loaded!"); updateLinks(); async function updateDom(path) { console.log("Updating DOM with content from: ", path); const res = await fetch(path); const data = await res.text(); const get = (o) => o; const parent = document.querySelector("html"); const currentNodes = document.querySelector("html").childNodes; const dataNodes = new DOMParser() .parseFromString(data, "text/html") .querySelector("html").childNodes; udomdiff( parent, // where changes happen [...currentNodes], // Array of current items/nodes [...dataNodes], // Array of future items/nodes (returned) get // a callback to retrieve the node ); updateLinks(); window.scrollTo(0, 0); } function updateLinks() { document.querySelectorAll("a").forEach((link) => { if (link.host === window.location.host) { link.setAttribute("data-internal", true); link.addEventListener("click", async (e) => { const destination = link.getAttribute("href"); e.preventDefault(); history.pushState({ route: destination }, destination, destination); await updateDom(destination); }); } else { link.setAttribute("data-external", true); } }); } window.onpopstate = function () { updateDom(window.location.pathname); }; };