Script registration labyrinth – startup scripts and $find (alternative)

I described a universal way how to register startup script that invokes $find javascript function. This solution is taken from AJAX Control Toolkit and looks like this:
(function () {
    var fn = function () {
        var control = $find('someControl');

There are other possibilities. I found a solution proposed on Telerik’s forum: use setTimeout javascript function to postpone the execution of $find until all controls are instantiated by $create functions.
The trick is used by Telerik ASP.NET Ajax controls, particularly for scripts registered into RadAjaxManager.ResponseScripts collection. If you try this fragment:
string script = string.Format("alert($find('{0}'));", Control1.ClientID);

It will result into this output:
setTimeout(function(){alert($find('Control1'));}, 0);

It works well for partial postbacks but not for full postbacks. No surprise there because RadAjaxManager is inherently tied to partial postbacks. It can be used for full postbacks as well anyway. It is a pitty because there is no unified way how to register startup scripts for both postback types in Telerik ASP.NET AJAX controls (at least in current version – 2012.1.411). You have to check the request type (GET/full postback vs. partial postback) and decide how to register the startup script.
It is so easy to fix this approach. Just wrap the setTimeout function to init event handler:
Sys.Application.add_init(function () {
    setTimeout(function () {
    }, 0);

Here is full markup and code-behind (Telerik ASP.NET AJAX controls are required).

No comments:

Post a Comment