53 lines
1.6 KiB
JavaScript
53 lines
1.6 KiB
JavaScript
const content = document.getElementById('page-content');
|
|
const loader = document.getElementById('loader');
|
|
|
|
// Whitelist of pages: name -> file (and title)
|
|
const routes = {
|
|
home: { url: 'pages/home.html', title: 'Home' },
|
|
about: { url: 'pages/about.html', title: 'About' },
|
|
community: { url: 'pages/community.html', title: 'Community' },
|
|
blog: { url: 'pages/blog.html', title: 'Blog' },
|
|
join: { url: 'pages/join.html', title: 'Join' },
|
|
privacy: { url: 'pages/privacy-policy.html', title: 'Privacy Policy' },
|
|
};
|
|
|
|
let controller;
|
|
|
|
async function loadPage() {
|
|
const name = location.hash.slice(1) || 'home';
|
|
|
|
document.querySelectorAll('nav a').forEach(a => {
|
|
if (a.getAttribute('href') === `#${name}`) a.setAttribute('aria-current', 'page');
|
|
else a.removeAttribute('aria-current');
|
|
});
|
|
|
|
const route = routes[name];
|
|
|
|
if (!route) {
|
|
content.innerHTML = '<h2>Page not found</h2>';
|
|
return;
|
|
}
|
|
|
|
// Cancel the previous request if the user clicks quickly
|
|
controller?.abort();
|
|
controller = new AbortController();
|
|
|
|
loader.hidden = false;
|
|
try {
|
|
const res = await fetch(route.url, { signal: controller.signal });
|
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
|
|
content.innerHTML = await res.text();
|
|
document.title = `${route.title} | Alabama Progress`;
|
|
content.focus();
|
|
} catch (err) {
|
|
if (err.name === 'AbortError') return; // superseded by a newer request
|
|
content.innerHTML = '<p>Sorry, that page failed to load.</p>';
|
|
console.error(err);
|
|
} finally {
|
|
loader.hidden = true;
|
|
}
|
|
}
|
|
|
|
window.addEventListener('hashchange', loadPage);
|
|
loadPage(); |