Single page application using jQuery

Javascript, jQuery, 2015-06-17 00:06:39 UTC

Sometimes you see the URL format like this; http://example.com/#!/the_page. Usually, this is the Angular application. This is good technique to load the page faster than a standard technique.

In this tutorial, I want to show you how to create it and this technique is just using jQuery.
Let's take a look the advantage of using this technique;
1. You don't need to load resources multiple time.
2. The page loading faster than a standard technique.
3. This technique can be applied to various of script like Java Web, PHP, Rails, etc.
4. And the last, when the user sharing the page, the user will land on the right page. I will show you what I mean in the code comment.

Let's create it;

1. First, I will assume we need those URL;
http://example.com/#!/about
http://example.com/#!/inquiry_form


2. Create simple index.html page in your root folder.

<html>
    <head>
        <title>Simple page</title>
        <script src="jquery-2.0.3.min.js"></script>
    </head>
    <body>
        <div id="page"></div>
        <script src="app.js"></script>
    </body>
</html>



3. Create javascript app.js where the magic code place.

//javascript object
var core = {
    baseUrl: 'http://example.com',
    loadPage: function(thePage) {
        $.ajax({
            url: this.baseUrl+thePage,
            success: function(response) {
                $('#page').html(response);
            }
        });
    }
};

//Below code use for executing the right page when guest land directly
//ex; When the guest visit URL; http://example.com/#!/about, He/she will see about page.
$(document).ready(function () {
    var landingURL = document.URL;
              
    var arrURL = landingURL.split('!');
                
    var arrLength = arrURL.length;
                
    var thePage = arrUrl[1];
                
    if(arrLength === 1) {
        core.loadPage('/home');
    }
    else {
        if(arrURL[1] === "") {
            core.loadPage('/home');
        }
        else {
            core.loadPage(thePage);
        }
    }                                
});



4. Now we can create pages; home, about and inquiry_form
For these pages, you don't need to include another resource in your page.
Let say, I use a PHP script for about page. So, the page name is about.php and look like below

<div id="about">
    <h1>About</h1>
    <article>Lorem ipsum sit dolor amet .....</article>
</div>



That's it!

Last, for advantage technique, loading page more faster, you can improve using API technique. The response from the API can be JSON, parse it and put it on the right HTML element.


Share: