In the world of Single Page Applications (SPAs), managing routes without a framework can seem daunting. But with Vanilla JavaScript, you can create a simple yet powerful routing system! ?
Here’s a quick guide to get you started:
Routing in an SPA involves mapping a URL to a specific view or content. Instead of reloading the page, the app dynamically updates the content based on the URL.
<div> <h3> <strong>Step 2: Create the Router</strong> </h3> <pre class="brush:php;toolbar:false">class Router { constructor(routes) { this.routes = routes; this.init(); } init() { window.addEventListener("hashchange", () => this.handleRouteChange()); this.handleRouteChange(); } handleRouteChange() { const currentPath = window.location.hash.slice(1); const route = this.routes[currentPath]; if (route) { route(); } else { this.routes["/404"](); } } } // Usage const router = new Router({ "/": () => (document.getElementById("root").innerHTML = "Home Page"), "/about": () => (document.getElementById("root").innerHTML = "About Page"), "/404": () => (document.getElementById("root").innerHTML = "404 Page"), });
? Pro Tip: If you're building a larger app, consider modularizing your code and handling edge cases like query parameters or nested routes.
Have you ever built your own routing system? Share your experience in comments! ?
The above is the detailed content of A routing system in JavaScript for Single Page Application. For more information, please follow other related articles on the PHP Chinese website!