Building a Single Page Webapp with jQuery

In a typical single page web app, you load a html page and keep updating it by requesting data from the server either periodically or whenever the user asks for. Such an application is well suited for data driven systems. For example, if you already have a REST API, you can easily create a single page web client for it. The best way of understanding what a single page web app is by looking at the web interface of Gmail

So let us define what we want to achieve in the end with our application:

  • We should be able to load different views on the same page.
  • We should be able to translate user intentions (clicks) into appropriate javascript function calls.
  • The url shown in the address bar of the browser should represent the state of the application. That is, when the user refreshes the browser, it should have the same content as prior to refresh.

The Root Page

So let us begin by defining the basic structure of our application. index.html is our application page that will be modified during the lifetime of our application. For the sake of simplicity, let us assume that we will be making changes to #application div only.

Intercepting link clicks

Now we need to intercept all the click actions on the links and change the url hash accordingly. For handling the url hashes, we are using the Jquery BBQ plugin. Intercepting the link clicks will help us in preventing the default navigation to other pages. Also, as this is the required behaviour for all the links, we will setup the interceptor at global level. If required you can change the scope of this interception by modifying the jQuery selector where we define the interception.

Defining the Routes

Next, we need to define the routes that are mapped to url hash. Also, since each hashchange represents an action on part of user, we will also define what function to execute for each hashchange. We do this by listening for haschange event and firing the appropriate js function.


Even though, we have proper routes and actions defined now, our index page is still empty. We now need to initialize the app. This is done by setting the default hash, which will fire the hashchange event when the page loads or in case the user has refreshed the page, just triggering the hashchange event manually.

Sample Action

Now that we have the skeleton for our application ready, lets have a look at a sample action. Suppose the default action, is showing a list of users [#/users]. We have mapped this hash to the function showUserList. Now there are several ways of combining the html structure and the json data for userList, but we will be using the simplest of methods. First we will get the html fragment representing the userList using the $.load function, and then we will populate it with actual data that we get from the REST api.

var showUserList = function(){
	$('#app').load('/html/users.html #userListDiv', function() {
		$.getJSON('/users', function(data) {
			// create the user list
			var items = [ '<ul>'];
			$.each(data, function(index, item) {
				items.push('<li><a href="/users/"' + + '">'
						+ + '</a></li>');
			var result = items.join('');
			// clear current user list
			// add new user list

If you find all the string concatenation going on in above snippet a bit sloppy, you can always use your favourite template plugin for jQuery.

Note: The Object.extended function in above snippets comes from the wonderful Sugar.js library that makes working with native javascript objects a breeze.

Role based views using css and javascript

In web applications, role based views are normally done using server side if..else tags etc. When developing pure javascript clients, one way of doing role based views is again using javascript conditionals. This approach suffers from the fact that role-related code is scattered throughout the document. Another simple way to achieve the same is using css classes.

Let us assume that we have three roles, ADMIN and USER and GUEST. Then we will define three css classes as follows:

Now consider the following html doc, that has css classes attached to elements according to the current user’s role.

At this stage if you load the document in a browser, you will not see anything as nothing all the roles are invisible. So lets spruce this up with a bit of javascript to set proper css class properties.

If a cookie role is set that represents the current user’s role then adding the above snippet of code will enable all the elements tagged with css class .role_{roleCookie} to be visible.

Even though this is a very simple implementation, we can modify it easily to take into account more complex scenarios. For example, if you have completely ordered role based visibility (access level), i.e. given role R1 and R2, we can always tell which role has more visibility, then we can extend as follows:

$(document).ready(function() {
    // We are assuming that jQuery and jQuery Cookie plugin are included in the doc

    var role = $.cookie('user_role'); // Should return one of 'ADMIN', 'USER' OR 'GUEST'

    // set property for relevant css class
    if(role == "ADMIN") {
        // make everything visible
        $("<style type='text/css'>.role_admin, .role_user, .role_guest {display:block} </style>").appendTo("head");

    } else if(app.role == "USER") {
        // make user and guest part visible, admin part will remain invisible
        $("<style type='text/css'>.role_user, .role_guest {display:block} </style>").appendTo("head");

    } else if(app.role == "GUEST") {
        // only show the guest part
        $("<style type='text/css'>.role_guest {display:block} </style>").appendTo("head");

Caution: One thing to note here is that all the parts of the document are sent to all the users, only what is visible on the browser is role based. So, server side authorisation checks will always be there as nothing stops a suspecting user from looking into the source and firing that dreaded request.

Bing/Google toggle bookmarklet

I’ve been trying out Bing as my default search engine for last few months and the results are definitely at par with that of Google for most of the consumer categories. But sometimes you just need a quick toggle to see what Google would return for your query. So here is a small bookmarklet that I wrote that toggles from Bing to Google and vice versa.

Drag this to you favourites bar: Bing/Google Toogle

Note: Its tested on IE8 only. A few tweaks might be required for Firefox.

Minifying Javascript/css without changing file references in your source

Rule 10 of Steve Souders High Performance Web Sites: Minify Javascript

The most common problem faced while implemnting this is how you handle the full and minified version and how to change there reference in referencing documents. One of the easier ways to do this is to make it part of the deployment process.

Here are the relevent steps involved.

I’m using YUI Compressor.

#Execute this script after checking out the latest source from repository.
#Minify all javascript files
cd /path/to/javascript
for x in `ls *.js`
        java -jar /path/to/compressor/yuicompressor-2.4.2.jar -o ${x%%.*}-min.js --preserve-semi  $x
#Minfiy all css files
cd /path/to/css
for x in `ls *.css`
        java -jar /path/to/compressor/yuicompressor-2.4.2.jar -o ${x%%.*}-min.css  $x

Now you don’t want to replace all references to x.css or x.js in your development code with references to x-min.css and x-min.js respectively. So what you can do is rewrite all those filenames at the web server level.

For apache the following rewrite rules work fine:

#enable rewriting
RewriteEngine on
RewriteRule /(.*)\.js /$1-min.js
RewriteRule /(.*)\.css /$1-min.css

Caution: Remember to delete existing minified css/js file before running the minifying script or you will end up with file names like x-min-min-min.js and so on. One way to do this is to clear the js/css folder before checking out files from your source repository.