SPA Navigation
SPA Navigation
Section titled “SPA Navigation”Introduction
Section titled “Introduction”Single-page applications use the History API to create smooth, client-side navigation without full page reloads.
Basic SPA Navigation
Section titled “Basic SPA Navigation”function navigate(url, state = {}) { history.pushState(state, '', url); render(url); // Update page content}
window.addEventListener('popstate', () => { render(window.location.pathname);});Full SPA Example
Section titled “Full SPA Example”const routes = { '/': () => import('./pages/home.js'), '/about': () => import('./pages/about.js'), '/contact': () => import('./pages/contact.js')};
// Navigate without page reloaddocument.querySelectorAll('a[data-link]').forEach(link => { link.addEventListener('click', (e) => { e.preventDefault(); const url = link.getAttribute('href'); navigate(url); });});
async function navigate(url) { history.pushState({ url }, '', url); const page = routes[url]; if (page) { const module = await page(); module.render(); }}
// Handle back/forwardwindow.addEventListener('popstate', () => { navigate(window.location.pathname);});Summary
Section titled “Summary”- Use
pushStateto navigate without page reload - Update page content based on the URL
- Listen for
popstateto handle back/forward - Lazy-load page modules with dynamic imports for performance