Hash Routing

Hash Routing

What is hash routing?

Table of contents

No heading

No headings in the article.

Hash routing is a technique used in web development to create single-page applications (SPAs) where the routing is handled entirely on the client-side using URL hashes (fragments). Here's an example of how you can implement hash routing with templates using JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hash Routing Example</title>
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="#/">Home</a></li>
                <li><a href="#/about">About</a></li>
                <li><a href="#/contact">Contact</a></li>
            </ul>
        </nav>
    </header>

    <div id="content"></div>

    <script>
        // Define routes and corresponding templates
        const routes = {
            '/': '<h2>Home Page</h2><p>Welcome to the home page!</p>',
            '/about': '<h2>About Page</h2><p>Learn more about us.</p>',
            '/contact': '<h2>Contact Page</h2><p>Contact us for any queries.</p>'
        };

        // Function to render template based on current route
        function renderContent() {
            const hash = window.location.hash;
            const content = document.getElementById('content');
            if (routes[hash]) {
                content.innerHTML = routes[hash];
            } else {
                content.innerHTML = '<h2>Page Not Found</h2><p>The requested page does not exist.</p>';
            }
        }

        // Event listener for hash change
        window.addEventListener('hashchange', renderContent);

        // Initial rendering
        renderContent();
    </script>
</body>
</html>

In this example:

  • The navigation links use hashes (#/) to specify different routes.

  • The routes object maps each route to its corresponding template.

  • The renderContent() function extracts the current route from the hash, retrieves the corresponding template from the routes object, and updates the content of the #content element.

  • An event listener is added to listen for hash changes (hashchange event) and trigger the renderContent() function accordingly.

  • The renderContent() function is called initially to render the content based on the initial hash (if any).

This is a simple implementation of hash routing with templates in JavaScript. In a real-world application, you might want to use a more sophisticated routing library like React Router or Vue Router for better management of routes and components.