Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save virajkulkarni14/80d8914bc158e5a315756e6660ad0d7b to your computer and use it in GitHub Desktop.

Select an option

Save virajkulkarni14/80d8914bc158e5a315756e6660ad0d7b to your computer and use it in GitHub Desktop.

Revisions

  1. @kartiknair kartiknair created this gist Jun 21, 2020.
    48 changes: 48 additions & 0 deletions spa-navigation-for-static-links.js
    Original 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);
    };
    };