Attach JavaScript during Async Postback

JavaScript files can easily be attached to any document using the usual html code:

  1. <script src="Scripts/jquery.blockUI.js" type="text/javascript"></script>

Thats great…we all know that. But what if I want to dynamically attach a script file from codebehind. Thats an easy one too:

  1. if (!Page.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "Parameters"))
  2. {
  3.         Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "Parameters", Page.ResolveUrl("~/Scripts/Parameters.js"));
  4. }

Not too bad. The key here is that this code looks to see if the script is previously attached before including. Other versions of attaching scripts from codebehind have been depricated now. This code is great when creating isolated UserControl components – allows you to keep the JavaScript attachments isolated to inside the control.

Now the tougher question:

“How do I attach a script file dynamically during an async-postback?”

Since only the portion of content contained within an UpdatePanel is changed during an async postback, you cannot simply attach a script using previous methods. You need to utilize your script manager and update panel control to do this one:

  1. UpdatePanel upPanel = this.pnlUpdatePanel;
  2. ScriptManager.RegisterClientScriptInclude(upPanel, typeof(UpdatePanel), "Functions", Page.ResolveUrl("~/Scripts/Report.js"));
  3. ScriptManager.RegisterStartupScript(upPanel, typeof(UpdatePanel), "InitFunctions", "<script type="text/javascript">ShowReports()</script>", false);

First, you need a handle to your update panel (in this case my update panel id is: “pnlUpdatePanel”). Then simply call the ScriptManager method depending on the operation you want to do. The first method above will include an entire script. The second will register a text block script that you can include and write javascript too.

However, there is one last key piece of information you should be aware of. In .NET 3.5 this is not an issue, however in the newest SP1 a bug arose that caused a JavaScript error as follows:

this._currentTask is null

This can be resolved by notifying the JavaScript script manager of the script you have injected being fully loaded. Place the following line as the very last line of each script you attach:

  1. if (typeof (Sys) !== ‘undefined’) Sys.Application.notifyScriptLoaded();

If you don’t place this line…you will likely receive the above error and the script will not be loaded. If your javascript debugging is disabled….your page will simply act as if the script was never attached.

Leave a Reply