Friday, November 27, 2009

Use Sys.Application.add_load instead of $(document).ready()

I use the Telerik ASP.Net control suite in my application as well as jQuery.  Everything had been working just fine.  It is very common that I would write code that needed to be run once a page was loaded and I was using the jQuery ready() function like this:

$(document).ready(function() {
    ... // My initialization code here 
});

This was working great for  a while.  That is until I decided that I wanted to write some script that interacts with the Telerik RadDatePicker.  I had a RadDatePicker on my page and at one point I wanted to write some code that would read the selected date of the RadDatePicker so I was using the following code:

$find('<%= MyControl.ClientID %>').get_selectedDate();

I do my development in Firefox and this was working fine.  But when I tried to test the page in Internet Explorer, the $find method was returning null.  I searched around trying to figure out what was going on.  I finally discovered that I needed to use the Sys.Application.add_load method like this:

function initDates() {
    $find('<%= MyControl.ClientID %>').get_selectedDate(); 
}

Sys.Application.add_load(initDates);

While this technically worked, in my application I use UpdatePanel's and I was already catching the pageLoad event and firing it through jQuery as such:

function pageLoad() {
        $(document).trigger("pageLoad");
}

I do this so that I can write code in my UserControl's  like this:

$(document).one("pageLoad", function() {
    .. // My UserControl initialization code.
});

So since I already had a framework for hooking into the client-side page load event, I didn't actually need to use the Sys.Application.add_load method.  I hope this helps someone.  I had a very frustrating time dealing with this annoying problem.

To summarize, you can't use the onload event to interact ASP.NET AJAX client-side Components because they are not initialized at that point.  Now why it was working in Firefox is still a mystery to me, but I would still avoid it.

For a more detailed description about these two methods of running code at startup, check out this article.