Saturday, December 13, 2008
by
ASP.NET AJAX Team
|
Comments
In the past developers used <body onload="..."> to execute some script as soon as the page is loaded. Nowadays this is rather old-fashioned, no matter how you look at it. What's more, it doesn't work as expected in ASP.NET AJAX websites. Consider the following example:
| <body onload="MyFunction()"> |
| |
| <script type="text/javascript"> |
| |
| function MyFunction() |
| { |
| var myAjaxControl = $find("myAjaxControlClientID"); |
| myAjaxControl.doSomething(); |
| } |
| |
| </script> |
| |
| </body> |
The client-side page load event is fired by the browser as soon as all HTML and scripts have been loaded. However, this happens before the controls' client-side instances have been created. As a result, myAjaxControl will be null and the doSomething() method will trigger a Javascript error. So, a lot better approach is:
| <body> |
| |
| <script type="text/javascript"> |
| |
| Sys.Application.add_load(MyFunction); |
| |
| function MyFunction() |
| { |
| var myAjaxControl = $find("myAjaxControlClientID"); |
| myAjaxControl.doSomething(); |
| } |
| |
| </script> |
| |
| </body> |
In this case MyFunction() will be executed after all client-side control instances have been created and the script will work as expected. Another benefit of using the second approach is that multiple event handlers can be added to the client page load event, whereas only one handler is added if <body onload="..."> is used.
On a side note, you might also want to try a Telerik productivity tool - JustCode. It’s a Visual Studio add-in that offers advanced JavaScript code navigation,
refactorings, quick fixes and code analysis features which can help
you be more productive writing JavaScript code. What’s more JustCode can
be used for multi-language solutions, as it also provides features for
C#, VB.NET, ASP.NET, XAML and HTML.