NovoGeek.com - Krishna's weblog

A technical blog on jQuery, AJAX, JavaScript & modern web technologies

"Global variables are evil" is what the JavaScript Guru Douglas Crockford says, as they are the source of unreliability and insecurity. How elegant your code would be if you wrap your entire project's code under a single global namespace?

[Did you know? The entire JavaScript code of Yahoo's website is accessible through a single global 'YAHOO' object!]

In this article, I would like to show how you can create a chainable JavaScript library(not a library exactly, but sort of a toolbox) specific to your project. The concept is nothing new., this is how libraries like jQuery are built. It is more about understanding certain design patterns in JavaScript.

The first thing to know is:

(function(){ 
    //your code here....
})(); 

This is nothing but a self executing anonymous function. All it does is, it simply executes whatever code you write inside it and disappears after that. The private variables declared inside this function are not exposed to the global scope, unless specifically attached to the window object.

The next thing to know is about Prototypal Inheritance in JavaScript. This is a huge topic in itself and the article assumes that the reader is familiar with this concept. The idea is, in our anonymous function, we would have a private function and prototype it with our custom functions.

This is how our JavaScript toolbox looks like: 

(function(){
    var mySpace=function(){
        return new PrivateSpace();
    }
 
    var PrivateSpace=function(){
    };    
 
    PrivateSpace.prototype={
        init:function(){
            console.log('init this:', this);
            return this;
        },
        ajax:function(){
            console.log('make ajax calls here');
            return this;
        },
        cache:function(){
            console.log('cache selectors here');
            return this;
        }
    }
    window.my$=mySpace();
})();

In the above code, "PrivateSpace" is a private function which is prototyped with our desired functions. "mySpace" is a function which returns a new instance of "PrivateSpace" when executed.

As said before, our anonymous function executes once and does not expose these functions to the outer world. To expose our functions under a namespace, we should add the instance of our "PrivateSpace" to a window level(global) object. This is exactly what the last line of the code does.

So, when we say

window.my$=mySpace(); 

we are executing "mySpace()", which returns a new instance of  "PrivateSpace()" function and assigning it to "my$", which is a window level object. So if you print my$ like:

console.log(my$);

, you would get all the functions present in the "PrivateSpace()" prototype. So you can call your functions like: my$.ajax(), my$.cache() etc.

Note that each function in "PrivateSpace()" returns "this". i.e., each function returns an instance of "PrivateSpace()" and hence you can chain your methods like:

my$.init().ajax();

That's it! Now we have our own JavaScript toolbox specific to our project! So no more global functions in our projects. As said, this is nothing new to the JavaScript world,  this pattern is what jQuery uses for chaining the methods.

I have faced few problems while opting for this pattern and posted them in StackOverflow. Folks there are kind to answer and hence this article. I'm no JS guru to say this is 100% perfect, but I have implemented this without any issues in a huge project.  You may refer Chapter 6 (Chaining) in  Pro JavaScript Design Patterns which explains about this jQuery like pattern.

Do you have better ideas? Please let me know.

Happy coding :)


In my previous article, I have discussed about few scenarios where AJAX can be an overkill for our web apps. I would like to add few more such scenarios in this post.

(4) Heavy dropdowns: 

A dropdown control enforces the user to select a value, preventing the entry of unwanted choices. This would make sense if a dropdown has limited options. But we tend to populate the dropdown with hundreds/thousands of options (probably this is the case with list of all cities in a country).

The scenario gets worse when we make an AJAX call to fill such huge dropdowns. There are many articles which show 'how to fill a dropdown using AJAX', but none of them stress on the limit of options. So, for a dropdown with 3000 options you are adding 3000 DOM elements, thereby degrading the performance of your page. Imagine 5 such dropdowns in a page!

Another scenario could be a row having a dropdown with 300 options, which repeats for ‘n’ times! These are unseen dangers which slow down your site.

Bottom line: Use dropdowns when you want to display limited(say ~50) elements. For anything more than this, use auto complete feature(You may choose between local/remote data based on number of records). The same rule holds good for cascading dropdowns. Keep your DOM as small as possible!

(5) Accordions: 

This is another beautiful UI technique almost similar to Tabs, the main difference being-tabs appear horizontally whereas accordions appear vertically. The problems faced in accordions are exactly the same ones which I have explained for tabs (please refer to my previous article).

Bottom line: If your page is too huge, do not fetch the entire DOM for building an accordion. On page load, build accordion structure and fetch the content of first pane only. On clicking the next header, remove markup from the previous pane and populate the current pane. This way, your page will always contain limited number of elements(though huge DOM manipulations can cause a little delay).

(6) Page load AJAX Calls/Multiple domains:

If you profile most of the web apps, they make a number of AJAX calls on page load for business functionality. e.g., If you are trying to fill 5 dropdowns on page load using AJAX calls, you are inviting performance problems.In most cases, we can get rid of such calls by injecting JavaScript objects into the page

Bottom line: If AJAX calls on page load are still unavoidable, instead of making multiple calls, make only a single call. In your web method, hit multiple controllers and fetch the desired response and club the responses using .NET’s Dictionary object. This way, you will reduce some network traffic.

You may also try to move some of your web services to different domains and access the data through JSONP.  The maximum number of parallel calls per domain in IE8/FF3 are 6. This means, by chance if you are making more than 6 AJAX calls, the remaining would be queued. By splitting your services across multiple domains, you can still make more than 6 calls in parallel!

On a closing note, I think I’m writing more of theoretical aspects without any code, but I don’t want to lose these experiences in the darkness of my memories. Following these simple guidelines helped me solve many performance bottlenecks in a large scale project. I feel this would be useful for developers at all levels while taking design decisions. Do let me know your views!

Follow me on twitter for live updates. Happy coding :)


AJAX libraries have simplified developer’s life by providing clean & easy-to-use API. Their usage is so simple that we developers over use it, without realizing the performance impacts. In this article, I would like to explain few scenarios in which AJAX can be an overkill for your web apps.

The motto is to help fellow developers take better design decisions at an early stage, rather than repenting and fine tuning later. Below are real time problems, faced in a large scale ASP.NET/jQuery AJAX based web app, which should be given a serious thought:

(1) AJAX based navigation: 

“Keep DOM manipulations to the minimum” is what every JavaScript library says, but over use of AJAX based navigation defeats this purpose and you may rethink the design, unless your client specifically wants it.

If you are wondering what AJAX based navigation means, check jqGrid demos site. There are no post backs at all even while navigation. Content pages are fetched via AJAX and injected into a parent page, with a huge DOM manipulation.

If the page is small with very less number of DOM elements, AJAX navigation is fine. As the number of elements increase in the page, injecting the page takes longer time and beyond a point, causes ‘stop running script’ error, as discussed in my previous article. Typically, business applications contain hundreds of controls in a page, causing severe performance bottlenecks.

If you see Facebook, the Home, Profile, Account etc links on the top do a full post back and fetch the page, while any other operation is an AJAX call, which is a cooler approach.

Bottom line: AJAX navigation has performance problems when pages are huge. But it can solve problems like maintaining state by storing data in DOM elements, reducing session variables and reducing load on the server. So weigh these choices before taking a call.

You may find the total number of elements in the page using the jQuery code, $(‘*’).length; So be cautious of this count while injecting a page. In a complex page like Yahoo.com, there are about 780 elements (each html tag corresponds to one element). Make sure your page is having not more than 1000 DOM elements. If the count is running into thousands, then split your pages.

(2) Client side templating:

If you liked asp.net repeater and are looking for client side templating, hold on! There is a difference between asp.net repeater and client side templates.

In the case of a repeater, processing takes place on the server and not much load is on the browser. However, in the case of templates, processing as well as injection is on the client. Imagine templating 100 rows, with each row containing 30 elements. You end up having 3000 elements which is alarming!

I can give you the example of twitter.com or facebook.com. Both have a ‘more’ sort of button at the bottom, which fetch more records. What happens if you want to see the posts of last ten days? You end up with thousands of DOM elements and your browser slows down.

Bottom line: In terms of performance, what is apparent to the developer is only the time taken to process the template. But what is hidden is, the time taken for clearing events, handling memory leaks, cleaning missing tags and injecting the template. All this happens in jQuery’s .html() method.

So, if you want to template huge data, make sure you are implementing pagination. Again, as in the above case, $(‘*’).length is the key.

(3) Tabs:

Thanks to this fancy UI technique, which gives a wizard sort of appearance to the content. If you are looking only at the fundo part of it, you are getting into problems! The scenario gets worst when you have AJAX tabs which fetch huge pages.

Let’s say each page has ~700 elements. So if you have 5 tabs, you are having ~3500 elements. Imagine having blur, click, live events for so many elements. It’s a complete mess! Also, you will be running into context related issues, since 2 tabs can have 2 different controls with the same ID. When you are on an active tab, the content of the rest of the tabs is only hidden, but not removed. So your app’s performance is bad yet again.

Bottom line: If you want to use tabs with optimal performance, make sure you are clearing the mark up of the tabs which are not active. At any point of time, make sure your $(‘*’).length is always less than 1000, for better results.

I think I have covered quite a lot. I’m still facing several bottlenecks in my beautiful project and trying to figure out the solutions with my architect. Will cover more scenarios in my next article.

Happy coding :)


Before starting with the article, I would like to share something which encouraged me a lot. Now I'm a Microsoft Most Valuable Professional (MVP) for ASP.NET. Thanks to Microsoft folks for recognizing my efforts. :)

 

Coming to the point., have you ever faced the below “Stop running script” error message in your thick client web apps? This is one of the most frustrating errors, which hangs the browser, spikes CPU usage and slows down your operations.

 

 

Nicholas C. Zakas has an excellent article on why it occurs in various browsers. In short, his research says that the error occurs in various browsers due to exceedingly high number of operations taking place(~5 million statements in IE), or due to script executing for a very long time(~10 secs in FF).

For best performance, Nich says that no script should take longer than 100 ms to execute on any browser, at any point of time.

 

Now, why should jQuery developers worry about this?

They should, because jQuery is made of nothing but JavaScript and chances of getting this error are more, if you don't understand the core methods properly. Let's see in detail what this means.

 

Take the below script as example. Execute in Firebug console or in IE8 script panel or simply copy/paste in a html file and open it.

(function exec(){ 
    var str=''; 
    for(i=0;i<10000;i++) 
    { 
        str+='<div>test div '+i+'</div>'; 
    } 
    $('body').append('<div id="TestDiv"></div>');
    $('#TestDiv').html(str); 
})();

Note: The above code might crash your browser. So please try in stand alone instance. If you are not getting the error or experiencing different behaviour, probably you have better CPU which does not spike up to 100% for this code. The point here is about wrong usage of code. So increasing the max condition should give the error. This analysis is as per jQuery version: 1.3.2.

 

What I'm doing here is pretty straight forward. Just looping and creating 10000 elements and injecting them into the DOM. Now, what's so important here?

It's just a simple piece of code. 10000 operations in a loop is way beyond the threshold of 5 million operations. When you run this code for the first time, browser stops responding and when you run this for the second time, you get the 'stop running script' error.

 

This might sound silly at a first glance. Such huge loops will obviously cause such errors. But what if you are doing this in your code without your knowledge? Do you know that this error occurs in several facebook apps & in twitter? There is something beyond the loop.

 

$().html vs element.innerHTML:

Replace the line:

$('#TestDiv').html(str);

with this one:

$('#TestDiv')[0].innerHTML=str;

and now try. We are using native JavaScript's innerHTML to inject DOM elements. This is faster than jQuery's .html() and hence no error.

 

Does this mean this is the mistake of jQuery?? No! It's purely developer’s ignorance. First of all, such huge DOM manipulations should not be made (This is commonly used, unknowingly.). Then, you should be aware of what .html() does.

 

$(‘selector’).html() internally removes event handlers attached to every child element in the selector’s DOM tree , cleans up the incoming mark up by adding unclosed tags and then injects the new mark up. So for the first time, since no DOM elements were there, .html() only cleans the new mark up and injects it. For the second time, it has the additional task of removing the event handlers and hence the number of operations are increased, giving the error.

 

So when should I use .innerHTML and when should I use .html()?

Genuine doubt! Use .innerHTML if you are SURE that you have to JUST replace the mark up, provided your mark up does not contain any events attached to it. Use jQuery’s .html() when you want to unbind events attached to elements and take care of garbage collection/memory leaks. (You may refer to “jQuery cookbook” for more info on this).

 

This is not the only pitfall. JavaScript’s native for(;;) loop is faster than jQuery's $.each() loop. So before enjoying the benefits of the library, analyze the bottle necks too.

 

(Q) When does such scenarios arise? Why would someone loop some 10000 times in their code?

(A) Though practically no developer loops ten thousand times in his code, knowing that it’s a performance issue, people tend to make this mistake unknowingly. The analogy here is about larger DOM manipulations. I shall explain such scenarios in my next article.

 

Happy coding :)


Happy to say that I have presented today in Microsoft Virtual Tech Days(VTD) on ASP.NET AJAX Library(BETA)Smile

You can download the presentation here: http://www.slideshare.net/novogeek/introduction-to-asp-net-ajax-librarybeta

I have also uploaded working demos. You can find them here: http://labs.novogeek.com/VTD18Mar2010/index.htm

Regarding the demos, I have converted the aspx files to .htm files, so that you can simply save the demos from the browser. (Same code as shown in VTD).

Please let me know in case of any issues. Thank you once again for the warm response Smile


Developers who have tried jQuery UI Tabs plugin might have tried AJAX mode, which is really useful in meeting several requirements. The documentation clearly explains how to start using AJAX tabs.  However, there would be few hiccups if the plugin is not clearly understood. Below are some of them which I have faced recently:

Problem 1: In AJAX mode, sometimes, tabs do not load on a single click. You need to select a tab twice (double click) to open a tab.

Reason: Unfortunately, this is due to a bug in the plugin and happens when your AJAX calls fail.  Error handling is not done properly in jQuery tabs plugin as of the current version(1.7.2). More about this bug here. It can be resolved by applying the patch as described in the ticket. Hopefully, it would be fixed in the next release.

Problem 2: The “spinner“ option does not work by default (Spinner lets you provide a default “loading…” message in the tab, during tab load).

Resolution: To show spinner, the content of anchor tags inside “<li>” must be enclosed in “<span>” tags. More info here…

Problem 3: Displaying custom “loading” message in the tab body (and NOT in the tab).

Resolution: Overwrite the default spinner and make use of “select”, “show” functions. More Info here…
(Note: When tabs are cached, “load” will not get triggered for the second time. So use “show” instead of “load” while caching).

Problem 4: Remove “flickering” of tabs on page load.

Resolution: As you might have expected, simply hide the tabs container using CSS (display:none) and show it using jQuery after tabs are built as below:

$('#TabsDiv').tabs({.....}).css('display','block');

Problem 5: Tab panel/body is not removed from the DOM when a tab is closed.

Resolution: This is indeed a tricky problem. This happens when tabs are disabled! Wondering what is the relation? It’s simple. When a tab is disabled, the “<li>” element, which makes the tab header, will be displayed in a dull style. But the corresponding “div”, which makes the tab panel/body is not rendered.

So, there would be a difference in indexing between tab header & body and thus the tab body is not deleted. Hence, do not disable tabs when you want to remove them based on index! (You may debug the first two lines of “remove:” function in the plugin to test this).

Problem 6: Prevent “auto selection” of adjacent tab, when a tab is closed.

Resolution: The Tabs plugin mimics “Firefox” tabs with respect to auto selection of a tab, when another tab is closed. However, sometimes, you might need to select a farther tab on closing of a particular tab. This cannot be achieved by overriding the “remove” callback. So simply comment the below lines in “remove” function and write your code to select the desired tab in your close button click event.

// If selected tab was removed focus tab to the right or 
        // in case the last tab was removed the tab to the left. 
        if ($li.hasClass('ui-tabs-selected') && this.anchors.length > 1) { 
            this.select(index + (index + 1 < this.anchors.length ? 1 : -1)); 
        }

Note: I’m using jQuery tabs inside UI.Layout plugin in my project. At first, I thought that the layout plugin is messing up my code and causing these issues. After straining for 3 days, I could figure out the above solutions. So folks using the UI.Layout plugin need not worry about Tabs plugin integration. Their combination works perfectly.

Hope this article saves the time of many enthusiasts who might face similar problems. Happy coding :)


If you are an ASP.NET web developer using jQuery for AJAX, you would have probably got used to passing parameters through DTO (Data Transfer Objects) as suggested by Dave in Encosia.com. This is a clean and simple approach for passing parameters from client to server.

Unfortunately, many jQuery plugins are not coded this way and need to be tweaked. Same is the case with jqGrid, which is an excellent jQuery grid plugin. So below are the simple tweaks to be made for jqGrid to support DTO's.

At a basic level, these tweaks should be  done in the "grid.base.js" file. If you are using plugins for inline edit or any other feature which makes AJAX calls, the same changes have to be made there also.

There are things which need to be changed in all AJAX calls made by the plugin:

1. Building a Data Transfer Object(DTO).

2. Setting the content-type to "application/json".

3. Convert the input object into  JSON string.

4. Filtering .NET's "d" parameter in the AJAX success function.

1. Building a DTO: In "grid.base.js", search for the code "populate = function() { ", which is the definition of populate function (This is in line 577). In this function, add the code in bold, above the switch statement (which is in line 588).

var jsObj = { 'obj': ts.p.postData }; //Building a DTO
switch (dt) {
                    case "json":
                    case "xml":
                    case "script":

2. Setting the content-type to "application/json":

  In line 593, add the JSON content type as a parameter to $.ajax function.

3. Convert the input object into  JSON string:

 In the same lin(593), replace the data parameter with JSON stringified DTO.

The code change for (2) and (3) will now be:

  Old Code:  $.ajax({url:ts.p.url,type:ts.p.mtype,dataType: dt ,data: ts.p.postData, 

  Tweaked code: $.ajax({ url: ts.p.url, type: ts.p.mtype, dataType: dt, contentType: 'application/json; charset=utf-8', data: JSON.stringify(jsObj),

 4. Filtering .NET's "d" parameter in the AJAX success function:

Finally, filter .NET's "d" parameter in the line 596 like below:

  Old code:   if(dt === "json" || dt === "script") addJSONData($.jgrid.parse(req.responseText),ts.grid.bDiv,rcnt);

  Tweaked code:  if (dt === "json" || dt === "script") addJSONData($.jgrid.parse(req.responseText).d, ts.grid.bDiv, rcnt);

That's it! The grid should now be able to handle JSON objects as input parameters and should bind JSON data successfully. Note that I have done these tweaks in jqGrid 3.5. The same concept applies to lower versions of jqGrid too. However, the line number and variables used in AJAX calls differ.

Hope this article would save the time of many enthusiasts, who want to use jqGrid in their ASP.NET projects. I shall come up with a detailed post on other common problems shortly.


In .NET 3.5, when a Web service class is decorated with “ScriptService” attribute, the web service returns data in JSON format [MSDN]. I have demonstrated this with a simple example in the article, Passing JSON objects in .NET 3.5.

Let us consider that our “person” class has several properties, of which only few are useful on the client side for data binding. We can filter this object in two ways:

1. On the server side:- Create a dictionary object [System.Collections.Generic.Dictionary(Of TKey, TValue)], add the desired properties to dictionary object and return it.

2. On the client side:- In cases where a quick filter has to be done without touching server side code, we can use jQuery’s each function to create a custom JSON object.

Suppose you want to filter only “country” and “code” out of the below JSON data,

var players = 
[{ "country": "India", "code": "Ind", "name": "Sachin" },
{ "country": "Sri Lanka", "code": "SL", "name": "Murali" },
{ "country": "Australia", "code": "Aus", "name": "Shane" },
{ "country": "West Indies", "code": "WI", "name": "Lara"}];

you can simply write the below jQuery code:

var newObject = {}; //Creating a new object
$.each(players, function() { //Looping through our players array using jQuery's each function
    newObject[this.country] = this.code; //Creating our custom "name/value" pair
});

So, our newObject will contain new data(having only “country” and “code”). If you want to access country code, you can simply say “newObject.India”, which gives “Ind”.

This tip is particularly useful in cases like filling dropdown lists with JSON data. By default, the server’s JSON data contains several properties which are not required. In such cases, this client side filter comes as a handy tip :)


I was trying to use jqGrid, an excellent jQuery based grid, for building a zero postback page. It's configuration is very simple, similar to flexigrid, but has many additional features like inline editing, subgrids etc.

What jqGrid expects is a JSON response having few objects and arrays, which are mapped to columns in the grid inside the grid.base.js file, like this.

Though the grid's AJAX call is successful, data is not being bound to thegrid. The reason is, .NET 3.5 returns JSON object which is prefixed with a "d" parameter like this.

So, to map the JSON data to the grid, we have to manually parse the AJAX response and separate the "d" parameter in AJAX success callback. This applies not only to jqGrid, but also to all jQuery plugins which expect JSON response.

I was about to write more on why .Net 3.5 prefixes "d" to JSON response, how it enhances security and how to parse it easily., but incidentally, Dave ward explained the concept excellently in his latest article: http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again

So no more worrying about .Net's "d" again :)


In my previous post, I have explained how to pass complex types using jQuery and JayRock in .NET 2.0 framework. I was digging a bit into Dave’s example (using complex types to make calling services less complex) in .NET 3.5 framework, to find how easier JSON serilaization/deserialization can be made.

When a Web service class is decorated with “ScriptService” attribute, which is in the System.Web.Script.Services namespace in .NET 3.5, the web service returns data in JSON format [MSDN]. Whether the returned value is a string or an object, it will be in JSON format. So no need of writing chunks of code for serializing objects explicitly.

Therefore, all that we need to do is to simply decorate our web service class with “ScriptService” attribute and  return an object from the server. So, to create a JSON object like this:

{"d":{"FirstName":"Krishna","LastName":"Chaitanya","City":"Hyd","State"
:"Andhra","Country":"India"}}

We can simply return a person object like this:

<WebMethod()> _
    Public Function fnFetchDetailsClass() As Person
        Dim objPerson As New Person
        Try
            objPerson.FirstName = "Krishna"
            objPerson.LastName = "Chaitanya"
            objPerson.City = "Hyd"
            objPerson.State = "Andhra"
            objPerson.Country = "India"
        Catch ex As Exception
 
        End Try
        Return objPerson
    End Function

In some situations (like in client side templating), we might need to create custom, complex JSON objects on the fly. In such situations, we can make use of .NET’s “ListDictionary” and “ArrayList” classes.

The above example can be re-written using ListDictionary as:

<WebMethod()> _
Public Function fnFetchDetails() As ListDictionary
    Dim jsonObj As New ListDictionary
    Try
        jsonObj.Item("fname") = "Krishna"
        jsonObj.Item("lname") = "Chaitanya"
        jsonObj.Item("city") = "Hyd"
        jsonObj.Item("state") = "Andhra"
        jsonObj.Item("country") = "India"
        Return jsonObj
    Catch ex As Exception
        jsonObj.Item("Error") = "Error at server"
        Return jsonObj
    End Try
End Function

Thus, using JSON is made easier in .NET 3.5.

Here is a simple demo which makes things clear. (I have used jQuery for making AJAX calls.)

(Note: ListDictionary stores values in Name/Value pairs, which is useful in building JSON Object. Similarly, an ArrayList can be used to build JSON Arrays. Therefore, these two can be used instead of JsonObject and JsonArray classes of Jayrock in my post Converting ASP.NET DataTable to JSON using JayRock.)


  • Share/Save/Bookmark
  • Entries (RSS)
  • Comments (RSS)

About

ProfilePic Hi, My name is Krishna Chaitanya and I'm a web developer from Hyderabad, India.

This is my online abode where I write about various technical topics, my little experiments related to web development in ASP.NET, jQuery etc. More...