Navigating Page w/o Leaving the Page using JS Fetch and History PushState Tutorial

In this tutorial, you will learn how to implement Page Navigation without actually leaving the page in a web application using JavaScript. This tutorial aims to provide IT/CS students and new programmers with a reference that might help them to achieve their desired web application projects. Here, step-by-step tutorials with snippets are provided. A sample application source code that demonstrates the objective of this tutorial is also provided and is free to download.

How does the Page Navigation w/o leaving the Page work?

Page Navigation w/o leaving the Page is a feature of an application that allows the user the navigate to a different page without actually leaving the actual page and reloading the assets. Basically, this kind of feature updates a certain part of the page interface template.

What are the benefits of implementing this Feature?

This feature is not required for implementing a web application but some developers implement this kind of feature to allow their end-users to navigate pages on the application faster. This feature minimizes the page assets reloading on the client side.

For example, your site or web application loads multiple assets (external CSS, JS, etc.) and some of these asset sizes are large. Loading your page content or navigating to other pages might take some time due to multiple and large sizes of assets that are needed to be loaded on the client browser. But if you implement this feature, assets will only load when the site was opened freshly or the users forcibly reload the page. Check out the sample snippet below to understand more.

Page Navigation w/o leaving the Page

Using the JavaScript built-in method and API called Fetch API and history.pushState method, this feature can be achieved easily. The fetch() API will get the page content that you need to display to your user while the history.pushState() method will update the page history state so that when the user reloads the page, the page will be loaded with the last content loaded.

Here are the steps for implementing this feature in a simple web application

Step 1: Create a Page Interface Template

The first thing you need to do is to create the page interface template. In the template, load all the assets you needed to load the other scripts you want to load on every page.

index.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>JS - Navigate Page using History State</title>
  7.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9.     <link rel="stylesheet" href="assets/css/styles.css">
  10.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  11.     <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  12.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  13.  
  14.     <script src="assets/js/script.js"></script>
  15.     <style>
  16.        
  17.     </style>
  18. </head>
  19.     <main>
  20.         <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
  21.             <div class="container">
  22.                 <a class="navbar-brand" href="./">JS - Navigate Page using History State</a>
  23.                 <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
  24.                     <span class="navbar-toggler-icon"></span>
  25.                 </button>
  26.                 <div class="collapse navbar-collapse" id="navbarNav">
  27.                     <ul class="navbar-nav">
  28.                         <li class="nav-item">
  29.                         <a class="nav-link" href="./?page=home">Home</a>
  30.                         </li>
  31.                         <li class="nav-item">
  32.                             <a class="nav-link" href="./?page=about_us">About Us</a>
  33.                         </li>
  34.                         <li class="nav-item">
  35.                             <a class="nav-link" href="./?page=policy">Policy</a>
  36.                         </li>
  37.                     </ul>
  38.                     </div>
  39.                 <div>
  40.                     <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  41.                 </div>
  42.             </div>
  43.         </nav>
  44.         <div id="main-wrapper">
  45.             <script>
  46.                 start_loader()
  47.             </script>
  48.             <div class="container px-5 my-3" id="contentContainer">
  49.                 <?php
  50.                $page = $_GET['page'] ?? "home";
  51.                if(is_file("./pages/{$page}.php")){
  52.                    include("./pages/{$page}.php");
  53.                }else{
  54.                    echo "<h1 class='text-center fw-bolder'>404 | Object not Found</h1>";
  55.                 }
  56.                 ?>
  57.             </div>
  58.         </div>
  59.         <footer class="bg-gradient bg-light shadow-top py-4 col-auto">
  60.             <div class="">
  61.                 <div class="text-center">
  62.                     All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-muted">JS - Navigate Page using History State</span>
  63.                 </div>
  64.                 <div class="text-center">
  65.                     <a href="mailto:[email protected]" class="text-decoration-none text-success">[email protected]</a>
  66.                 </div>
  67.             </div>
  68.         </footer>
  69.     </main>
  70.     <script src="assets/js/navigate-content.js"></script>
  71. </body>
  72. </html>

As you can see in the provided script, page contents are stored in the pages directory and loaded into the specific part of the template.

Step 2: Create your Page Content

Next, create your page's contents.

pages/home.php

  1. <div class="col-lg-10 col-md-12 col-sm-12 col-xs-12 mx-auto">
  2.     <h2 class="text-center"><b>Home Page</b></h2>
  3.     <hr>
  4.     <div class="card rounded-0">
  5.         <div class="card-body rounded-0">
  6.             <div class="container-fluid">
  7.                 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam mi, auctor non risus vel, blandit consectetur sem. Nulla varius vel elit in consectetur. Integer convallis sed mauris quis vestibulum. Quisque vel augue id arcu faucibus blandit. Nam egestas tempus ex at varius. Morbi accumsan hendrerit pellentesque. Nullam suscipit sem neque, eu hendrerit justo feugiat ut. Duis sollicitudin ut ex non luctus. Aliquam condimentum nisl in augue tincidunt accumsan. Donec mollis lacinia massa et tempor. Suspendisse eget urna sit amet justo eleifend rutrum sit amet sit amet justo. Nulla facilisi. Phasellus tempus ex neque, ac condimentum urna ornare feugiat.</p>
  8.                 <p>Phasellus lobortis imperdiet semper. Etiam posuere erat vel lobortis gravida. Nunc nec justo sollicitudin, egestas ex ut, iaculis justo. Nunc imperdiet risus in augue imperdiet interdum. Nunc id mollis sem. In hac habitasse platea dictumst. In congue erat id tellus tincidunt, at finibus arcu tristique. Sed sollicitudin dolor a magna finibus, tempor iaculis sem tempor. Cras mattis sapien a dolor porttitor egestas. Suspendisse mollis libero et interdum sollicitudin. Sed imperdiet iaculis vehicula. Praesent arcu nisl, blandit vitae purus id, pharetra bibendum diam. Duis fermentum faucibus turpis, ullamcorper rhoncus tortor sollicitudin in.</p>
  9.             </div>
  10.         </div>
  11.     </div>
  12. </div>

Step 3: Create the JavaScript

Lastly, create the JavaScript code that updates your page content.

navigate-content.php

  1.     /**
  2.     * Pages Links
  3.     */
  4.    const navigationLinks = document.querySelectorAll('#navbarNav .nav-link')
  5.    // Content Container
  6.    const contentContainer = document.getElementById('contentContainer')
  7.    const objectNotFound = document.createElement('h1')
  8.    objectNotFound.classList.add('text-center')
  9.    objectNotFound.classList.add('fw-bolder')
  10.    objectNotFound.innerText = `404 | Object Not Found`
  11.    
  12.    navigationLinks.forEach(link => {
  13.        // return false;
  14.        link.addEventListener("click", function(e){
  15.            e.preventDefault()
  16.            var redirect = this.getAttribute('href')
  17.        
  18.            // page to navigate
  19.            var redirect_url = location.origin + location.pathname + redirect;
  20.                redirect_url = new URL(redirect_url);
  21.    
  22.            // getting the page parameter
  23.            var _params = redirect_url.searchParams
  24.            var page = "";
  25.                if(_params.has('page'))
  26.                page = _params.get('page')
  27.            
  28.            //return 404 if page is empty or null
  29.            if(page == ""){
  30.                contentContainer.innerHTML = objectNotFound.outerHTML
  31.                return false;
  32.            }
  33.            //fetch the page content
  34.            start_loader()
  35.            fetch(`./pages/${page}.php`)
  36.                .then(response =>{
  37.                    if(!response.ok){
  38.                        //return 404 if page not found
  39.                        contentContainer.innerHTML = objectNotFound.outerHTML
  40.                        throw new Error("An error occured while fetching the page content")
  41.                    }
  42.                    return response.text();
  43.                })
  44.                .then( respBody => {
  45.                    // delay the redering of content for testing pusposes only
  46.                    setTimeout(()=>{
  47.                        // replace the page content
  48.                        contentContainer.innerHTML = respBody
  49.                        end_loader()
  50.                    },1000)
  51.                })
  52.                .catch(error=>{
  53.                    // delay the redering of content for testing pusposes only
  54.                    setTimeout(()=>{
  55.                        contentContainer.innerHTML = objectNotFound.outerHTML
  56.                        console.error(error)
  57.                        end_loader()
  58.                    },1000)
  59.                })
  60.                // Update history state [link on the address bar]
  61.                // - enables to load the page with the last loaded content
  62.                history.pushState({}, "", redirect_url.href)
  63.    
  64.          
  65.        })
  66.    });

I have provided also the source code zip file of the simple application that I created that demonstrates the objective of this tutorial. You can download it by clicking the download button located below this tutorial's content.

Here are some of the page snapshots of the sample application I created.

Page Navigation using JS

Page Navigation using JS

There you go! I hope this Navigating Page w/o Leaving the Page using JS Fetch and History PushState Tutorial helps you with what you are looking for and will be useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment