I am writing a small web app and I dont want to use a js framework. That’s why I am encouring some issues now.
The following snippet is responsible for the navigation. When a popstate event occurs, it show the spinner, initiates the page and shows it.
import spinner from "./pages/spinner/spinner.js";
import dashboard from "./pages/dashboard/dashboard.js";
import grid from "./pages/grid/grid.js";
const pages = {
dashboard,
grid,
};
window.addEventListener("popstate", async () => {
const body = document.getElementsByTagName("body")[0];
body.replaceChild(await createMain(spinner), document.getElementsByTagName("main")[0]);
const route = window.location.hash.replace(/#/g, "");
const page = pages[route];
const initiatedPage = await page.init(await createMain(page));
body.replaceChild(initiatedPage, document.getElementsByTagName("main")[0]);
});
history.pushState(null, null, "#dashboard");
window.dispatchEvent(new PopStateEvent("popstate", null));
async function createMain(page) {
const template = await fetch(page.templateUrl);
const main = document.createElement("main");
main.classList.add(...page.classes);
main.innerHTML = await template.text();
return main;
}
Problem:
- If a user now clicks a link twice the code inside the listener runs in parallel and have some side effect.
I need to find a solution where the second clicks stops the execution of the first one.
Do you have any ideas?