NovoGeek.com - Krishna's weblog

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

Happy to say that I have presented at Microsoft Community Tech Days 2010 on "jQuerify your ASP.NET apps" at Microsoft Hyderabad. The event, organized by Microsoft User Group Hyderabad (MUGH), had 400+ audience in Developer and IT Pro track!!

jQuery based PPT

Presentation: Click here

Demos:  Click here

I chose to prepare my presentation using jQuery itself, instead of power point, which would itself be a demo. The response from the audience was really encouragingSmile

Note: I used a lot of plugins in my demos but had to tweak them to meet my needs. So please don't use the versions which I am using in my demos as-is. Suggest you to download the original versions from the urls in the plugin files.

It was a great experience interacting with several enthusiastic developers and geeks. I've personally learnt a lot! Hope to meet you'll again. Please write to me in case of any doubts about using jQuery with ASP.NET

Happy coding Smile


Are you building a huge, jQuery-ASP.NET web application, which is subjected to a lot of global code changes in your client script? If yes, you should probably consider the below design pattern, which would help you have a better control on code execution.

Maintainability problem with large chunks of JavaScript code :

Imagine a web application having ~400 .js files. Each .js file would have code for AJAX calls/DOM manipulations for the respective .aspx page. But there would be some code which is redundant and can be moved to a common global function, which can be accessed by all .js files. With respect to ASP.NET paradigm, this can be compared to - your code behind partial class inheriting a base class. So whenever you have a global change, you can just change the base class and all .aspx files will have the changes.

However, there is a huge difference in the above comparison. ASP.NET has a powerful page life cycle which strictly defines which piece of code should be executed at what event. i.e., Pre Init, Init, Page Load, Pre Render etc. In the case of JavaScript, it is just dependent on ‘where you place your code’. i.e., even if you call a global function on line 1, developers can always add lines above and below it, which will mess up your code execution sequence.  This pattern is an attempt to have control on JS code execution, having Pre and Post events.

Solution- Using wrapper which can provide pre/post events:

Let’s say for every page, we need to prevent post back on click of any button. i.e., writing “e.preventDefault()” on button click events. I call this as a “Pre Event”, since this is to be executed before any click events are written.

Similarly, let’s say, for every page, we need to disable/show/hide certain controls, based on few conditions. I call this as a “Post Event”, since this code has to be executed at the end (similar to pre render event of asp.net model). So here is how we can try to enforce this.

Enhancing our chainable JavaScript library:

The following description is based on my previous article, building a chainable JavaScript library. For the global “Pre” and “Post” events, I’m going to extend the chainable JavaScript library with the “execute” method, like this:

(function(){
    var value='Hello world';
    var preInit=function(){
        console.log('pre Init');
    }   
    var preRender=function(){
        console.log('pre Render');
    }
    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;
        },
        setValue: function(newValue){
            value=newValue;
            return this;    
        },
        getValue: function(callbackFunc){
            callbackFunc.call(this,value);
            return this;    
        },
        execute:function(oldClass){
            preInit();
            var obj=new oldClass();
            obj.init.call(this);
            preRender();
        }
    }
    window.my$=mySpace();
})(); 

To explain the execute method, let’s consider the below code:

var CommonSearch=function(){
    var pageLoad=function(){
        console.log("page load operations here...");
    }
    return{
        init: pageLoad
    }
}

The above code is what resides in your ‘.js’ file. It is written in revealing module pattern. Here, CommonSearch is a constructor function and to execute it, we should say:

$(document).ready(function(){
    var objCommonSearch=new CommonSearch();
    objCommonSearch.init();
});

This does not have “Pre” and “Post” events. So if we need some global changes, we are lost! We have to manually change all 400 “.js” files. To troubleshoot this problem, if we use our my$.execute method, we can say:

$(document).ready(function(){
    my$.execute(CommonSearch);
});

Note that in the above snippet, we are not creating instance of CommonSearch constructor function. Instead, we are passing it to my$.execute, which internally calls the private “PreInit()” method first, then executes “init()” of  CommonSearch, and calls the private “preRender()” method. So, we are enforcing a particular sequence of code execution, which solves our problem.

[Note: As far as I know, 100% enforcement is impossible in JavaScript. If you are a JS Ninja, you can easily bypass whatever enforcement is set. That is the beauty of the language!!]

How this is different from using a common global function in document.ready, which can do the same functionality as my$.execute? Simple…we have good name spacing and chainability in our my$ function, which prevents conflicts with other modules.

If you are a JavaScript newbie, this article might sound a bit weird., but actually it is not so. I’m no JS guru to say this is the best approach. But this approach helped me a lot in scaling up easily and maintaining huge .js files, without any issues. If you can think of a better approach, please suggest. I’m waiting to learn..

Happy coding Smile


"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 :)


Function overriding is an important feature in any programming language. In advanced languages like .NET, Java, it can be accomplished easily through a set of key words. But this is not the same in JavaScript and this is where closures come to your rescue.

This article is not something new. Infact, it is a part of every JavaScript geek's  toolkit, which does not have much exposure. So just wanted to throw some light on it. (If you are not very clear of closures, please visit this article and come back).

Let us take a vey simple example. Assume that you have a button, for which a click event is bound.

<input type="button" id="btnTest" value="Test Button"/>

var originalClick=function(e){ 
    e.preventDefault(); 
    console.log('original button click'); 
}; 
 
$(document).ready(function() { 
    $('#btnTest').click(originalClick); 
}); 

Now, if there is some requirement change and you need to add extra functionality to this button click, then instead of messing up its method, you can extend the originalClick method using closures, like this:

(function() { 
    var extendedClick= originalClick; 
    originalClick= function() { 
        console.log('Extending Test Button click'); 
        return extendedClick.apply(this, arguments); 
    }; 
})(); 

The above code is nothing but a self executing anonymous function (gets executed immediately after its definition). In the first line, we are storing the actual function in a variable 'extendedClick' (we'l use this later). Then we are creating a function with the same name as our original button click function (originalClick).

In the inner function, we are writing our extended logic and executing 'extendedClick' using .apply() method. (passing 'this' as first param to .apply() makes sure that the context is still the same as original method). So the entire code would be:

var originalClick=function(e){
    e.preventDefault();
    console.log('original button click');
};
 
(function() {
    var extendedClick= originalClick;
    originalClick= function() {
        console.log('Extending Test Button click');
        return extendedClick.apply(this, arguments);
    };
})(); 
 
$(document).ready(function() {
    $('#btnTest').click(originalClick);
}); 

Thats it! Your method is now overridden!! Ok, now let us see what exactly happened.

As per the definition of closure, we have 2 functions which are nested and extendedClick is a local variable. The outer function is a self executing one. During its execution, ‘extendedClick’ is obviously available inside the inner function ‘originalClick’, since it is defined in the parent context. The magic of closure comes after the outer anonymous function is executed. How?

When you click on button, the overwritten ‘originalClick’ function will be fired, which will print the console statement ‘Extending Test Button click’. Then the ‘extendedClick’ function, which has a copy of the first ‘originalClick’ function, will be fired. But why is it still accessible? The variable ‘extendedClick’ is private to the outer anonymous function, which means, it should have been destroyed after the outer function executed. But it is still accessible, which is the power of closure.

(Q) How can I override core jQuery methods using this concept?
(A) Ben Nadel
explained it clearly in his article, which I happened to see while I started this article. It is the same concept, but still I wanted to write and explain in layman’s terms. Thanks to Ben for his great blog posts and for quick turn out in times of need.

Using this technique, you can override even $(document).ready function! This would help you the most when you are in a maintenance project and have to do bulk changes in code with minimal impact.

Happy coding :)


First of all, my Happy New Year wishes to all netizens! As you journey through 2010, leave a trail of hardwork, innovation, passion and excellence...

Coming to the topic, in web apps, most of the times, we would require adding and removing controls to a web page dynamically. E.g.,adding "Browse" buttons for email attachments(live mail, gmail etc). In a traditional ASP.NET app, we used to build a string containing markup and append it to some control. However, this requires postback. Here is the end result which we would want to achieve:

With the help of jQuery, we can achieve this functionality with ease. Let us see the various ways of implementing this functionality.

1. Using jQuery “clone(true)” function:

Many of us know about jQuery clone() function, which will clone any jQuery selector. But the hidden feature is, it accepts a boolean parameter. When the param is set to true, it will clone DOM elements along with their event handlers.

Though this method can help us achieve the end result, the disadvantage is, it will fail to initialize complex controls like date pickers, auto suggest textboxes etc.

2. Using jQuery “live” event:

jQuery live looks like a perfect choice for this requirement. Live events are added for current as well as future elements in the DOM and hence events for “+”, “-“ buttons can be written only once using Live.

Though this works as expected in simple screens, even this is not a perfect approach! If suppose you are loading pages via AJAX, the events would be bound multiple times. So clicking on “+” will add more than 1 row, as multiple click events are bound. This is because, Live adds events to the document and not to the element. Check this article to see how live works.

3. Using jQuery Event Delegation:

Yup! This will solve the problems caused by above methods. I don’t want to explain about event delegation as there are very good articles already available. Check these:

The concept is very simple. Suppose you have a html table with 100 cells and you need to fire an event when any cell is clicked, instead of writing the below code:

$('#myTable TD').click(function(){
    $(this).css('background', 'blue');
});

you can write code like this:

$('#myTable').click(function(e) {
    var clickedElement = $(e.target);
    clickedElement.css('background', 'blue');
});

So instead of binding 100 events as in case 1, you can achieve the same output by binding only a single event, as in case 2.

This will solve the problem of Live, as the events are not added at document level, but are added to parent container. This will also solve the problem of Clone as date pickers will be initialized properly.

DEMO: Here is a demo for the above functionality using LIVE (Use it only when you are not loading pages via AJAX). I shall very soon come up with a demo using event delegation. This is a real time problem which I faced in a large scale project. So wanted to share immediately, so that others might not fall in the traps in which I fell!

Happy Coding :)


Exception handling is an important feature in any business application. In simple words, it is all about catching ugly errors thrown by server and displaying them in a user friendly manner to the end user. (Of course, logging exceptions/notifications etc may also be a part of exception handling. )

ASP.NET provides API for handling exceptions and displaying them in custom error pages. Custom error pages can also be defined for different HTTP error status codes, which provides good experience to end users in case of exceptions.

However, if you are using AJAX in your ASP.NET application(I’m using jQuery library for AJAX), you would not like to redirect users to a custom error page, as that kills the primary motto of AJAX. You would instead like to display error messages in the same page, as in facebook or twitter. So here is how this can be done using jQuery:

jQuery’s $.ajax method has a special function, $.ajaxSetup, where global settings can be made for handling AJAX requests. If you use this global function, you need not write error callbacks for each of your AJAX requests. All erroneous AJAX requests will be handled by the global error callback in $.ajaxSetup function. We can take advantage of this and write our exception handling wrapper.

$.ajaxSetup({
    error: function(XHR, errStatus, errorThrown) {
 
        if (XHR.status == 0) {
            alert('You are offline!\n Please check your network.');
        } else if (XHR.status == 404) {
            alert('Requested URL not found.');
        } else if (XHR.status == 500) {
            var errorMessage = 'Internal server error';
            try {//Error handling for POST calls
                var err = JSON.parse(XHR.responseText);
                errorMessage = err.Message;
            }
            catch (ex) {//Error handling for GET calls
                $('#divMaster').append('<div id="divErrorResponse" class="DisplayNone">' + XHR.responseText + '</div>');
                errorMessage = 'Page load error: ';
                errorMessage += $('#divErrorResponse').find('h2 i').html();
            }
            alert(errorMessage);
        } else if (errStatus == 'parsererror') {
            alert('Error.\nParsing JSON Request failed.');
        } else if (errStatus == 'timeout') {
            alert('Request timed out..Please try later');
        } else {
            alert('Unknown Error.\n' + XHR.responseText);
        }
    }
});

In the above code, we are checking for status codes(which are self explanatory) and handling error conditions based on these codes. Most of the times, the status code will be “500”, which says “Internal Server Error”. i.e., error in your server side code. Please refer this article from Encosia.com, which explains the core of what I am writing now.

Now, this “500 – Internal Server Error” may arise in both GET as well as POST requests. In POST request, if your web method throws error, it returns a JSON object, which you can parse as explained in the above link. But this does not work in case of GET requests.

Assume that you are loading a remote page into a master page using jQuery AJAX. If your “Page_Load” event throws exception, your response would be in HTML format (unlike the case of POST request, where the response is JSON object), which you cannot parse using JSON.parse or eval(). To differentiate between GET & POST responses, I’m simply using JSON.parse() in try() method. If it throws exception, it is surely due to a GET response, which is html. For better user experience, you may use jGrowl plugin for displaying error messages.

Conclusion: For exceptions in GET requests, you can query the resultant html using jQuery’s DOM selectors and display user friendly messages. For exceptions in POST responses, you can simply parse the resultant JSON object and display user friendly messages. If you feel there could be a better way of handling exceptions in GET requests, let me know.

Hope this article saves the time of folks who are facing 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 ASP.NET web apps, most of the times we would need to call JavaScript functions in page_load event of code behind, for various valid reasons. In such scenarios, we simply use .NET’s Register Script methods for emitting JavaScript code, which is absolutely fine.

If you are using jQuery, you would write the logical flow of events to be executed in $(document).ready() function. However, if you are using Register script methods with jQuery, the output will not be as expected. I have faced this problem yesterday and want to share the reason and simple solution.

.NET framework provides two methods for emitting JavaScript to the client. They are:

  1. RegisterClientScriptBlock (Client-side script is emitted just after the <form runat=”server”> tag)
  2. RegisterStartupScript (Client-side script is emitted just before the </form> tag)

Note: These methods are now moved to ClientScriptManager class from Page class.

The below screenshot explains the difference clearly:

 

Okay. Now that the difference between the two is clear, let us go forward. Consider the below simple JS code:

function fnTestScript(msg) {
    console.log(msg);
}
 
$(document).ready(function() {
    fnTestScript('This is from document.ready');
});

We am defining a method fnTestScript(parameter) and calling it in jQuery’s ready() function. Now, in page_load event of server, let us call this method using Register script methods.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       'Using "RegisterClientScriptBlock" method to emit JS code.
       Dim strScript As New StringBuilder
       strScript.Append("<script language='javascript'>")
       strScript.Append("fnTestScript('This is from RegisterClientScriptBlock');")
       strScript.Append("</script>")
       ClientScript.RegisterClientScriptBlock(Me.GetType(), "TestScript", strScript.ToString())
 
       'Using "RegisterStartupScript" method to emit JS code.
       Dim strScript2 As New StringBuilder
       strScript2.Append("<script language='javascript'>")
       strScript2.Append("fnTestScript('This is from RegisterStartupScript');")
       strScript2.Append("</script>")
       ClientScript.RegisterStartupScript(Me.GetType(), "TestScript", strScript2.ToString())
   End Sub

Can you guess what the output will be? Here it is:

RegisterScriptsOrder

The reason is simple. .NET is injecting the script inline, into the DOM. So its functions are called before $(document).ready(), which fires after DOM is loaded. This means, your logical sequence of JavaScript calls has gone for a toss!

The solution is even more simple. Just add $(document).ready() in your function definition:

function fnTestScript(msg) {
    $(document).ready(function() {
        console.log(msg);
    });
}

Now your sequence of JavaScript calls will be like this:

RegisterScriptsOrder2

Q: Can you call $(document).ready() multiple times?
A: Yes!
This is another difference between this method and JavaScript’s window.onload, which is rarely mentioned in articles. The order of execution depends only on the order in the code.

Hope this article saves the time of others who face similar problem!


  • 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...


Friends


Archive