Friday, 26 July 2019

Dynamically loading pages in jQuery

jQuery  Bootswatch  JavaScript 

In the web page design, it's convenient to have a navigation menu bar on top of the website to allow users to switch between different pages. In this post, we show you a general method in jQuery to implement the pages being dynamically loaded regarding the user selection.

We first create a folder for the demo, e.g. jquery-loading-pages-testing. Under this folder, create a subfolder named css for the CSS files. For fast setting up the web pages, we use the bootswatch theme, Cosmo, here. Go to the URL:, click "Cosmo" in the navigation menu bar on top of the website and select "bootstrap.min.css". It will download the CSS file, bootstrap.min.css, to the local drive. Copy this file to the subfolder css.

The bootswatch Cosmo theme

Under the folder jquery-loading-pages-testing, create the file index.html and copy the following code.

<!DOCTYPE html>
<html lang="en">
    <title>Loading Pages Testing</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- download the bootstrap.min.css from the Cosmo theme of -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script src=""></script>
    <script src="scripts/myscript.js"></script>
    <div class="container">
        <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
            <div class="collapse navbar-collapse" id="navbarColor01">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#" data-page="home">Home</a>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="about">About</a>
                <form class="form-inline my-2 my-lg-0">
                    <input class="form-control mr-sm-2" type="text" placeholder="Search">
                    <button class="btn btn-secondary my-2 my-sm-0" type="submit" id="search">Search</button>

        <div class="row content col-sm-12  text-left"></div>


The HTML code under <nav> tag are from the source code of the blue Navbar in the Cosmo theme of Bootswatch. As shown in the screenshot below, if you click the sign <> at the top-right corner of the blue Navbar, it will show the relevant HTML source code.

The bootswatch Cosmo theme Navbar

The Navbar source code is simplified with only two navigation items, Home and About, to show the function for dynamically loading pages. In the file index.html, the code <div class="row content col-sm-12 text-left"></div> define the section where the pages will be dynamically loaded, when the user selects different navigation items.

We then create two HTML pages for the Home page and About page. In the same folder with the file index.html, we create the file home.html with the following HTML code:

    <p>Welcome to the Home page.</p>

For the About page, we create the file about.html with the HTML code below:

    <p>This is the demo for dynamically loading pages in jQuery.</p>

Under the folder jquery-loading-pages-testing, we create another subfolder called scripts and, in this subfolder, create an empty file named myscript.js. This is the javascript file that implements the function of loading pages dynamically. Copy the following code and paste it in the file myscript.js.


    var activeNavItem = localStorage.getItem("activeNavItem");
    if (activeNavItem) {
        if (activeNavItem != "home") {
            $("[data-page=" + activeNavItem + "]").parent("li").addClass("active");

        $(".content").load(activeNavItem + ".html", "RN" + Math.random()*10000);

    } else {
        $(".content").load("home.html", "RN" + Math.random()*10000);

    $(".navbar-nav a").on("click", function(){
        $(".content").load($(this).attr("data-page") + ".html", "RN" + Math.random()*10000);
        localStorage.setItem("activeNavItem", $(this).attr("data-page"));


In the source code, localStorage is used to save the selected navigation item. The value is saved with the key activeNavItem. In line 3, the localStorage's getItem() function is called to check whether the user's selection has been saved. If the variable activeNavItem returns with the value of null, it means that it is the first time the website is accessed. Therefore, the home page, home.html, is loaded by calling the method .load() in line 13. If the variable activeNavItem comes back with the value of the selected page name, just load the HTML file whose name is the same as the value (as shown in line 10). Since, in the file of index.html, the home page is made active by default,

<li class="nav-item active">
    <a class="nav-link" href="#" data-page="home">Home</a>

if the user selects the page other than "home", we need deactivate the "home" item by the code $("[data-page=home]").parent("li").removeClass("active"); in line 6.

We also need to implement the jQuery .on() method to handle the click event for the navigation menu bar when the user clicks the items. As shown in Line 17-20, the current selected item is deactivated, the item being clicked is made active and the relevant HTML file is loaded. Finally, the user's selection is saved with the key activeNavItem by calling the localStorage's method setItem().

When the .load() method is called in jQuery, the page is loaded from the cache by default. In order to refresh the page content when the page is loaded each time, we can add the optional data parameter in the .load() method. As shown in line 10, 13 and 19, we pass an unique string value, "RN" + Math.random()*10000, into the .load() method. We call the JavaScript's Math.random() function to generate a random number between 0 and 1. After multiplying the random number by 10000, we make a unique string value by adding a prefix of "RN" (of course, you can use whatever prefix you want here).

Now it's done. As shown in the screenshots below, when the user click "Home" or "About" in the navigation menu bar on top of the website, relevant page is loaded and the selected item is highlighted in white.

Home page is loaded

About page is loaded